When writing a CLI application there are some Ruby gems out there that make a big difference. TTY-prompt is without a doubt one of the most popular CLI gems out there - and for good reason. TTY-prompt is extremely helpful for reducing user error which makes your code harder to break since the user is no longer typing directly into the command line to make a selection. And, I think, improves the user experience which is important even in a small-scale application like this.
Basically, the TTY-prompt gem works by reformatting the output to let the user scroll through a list of options and make a selection. Here is a classic example of the TTY-prompt in action:
However, if your app is like mine you’ll need these lists to be dynamic. If your seed data changes, or if the selection list is determined by user input, you’ll code that’s more flexible than the examples given to you in the TTY-prompt documentation, that looks a lot like the main-menu example above.
Creating a dynamic list with TTY-prompt:
My partner and I managed it by splitting it up into three methods:
- Create a dynamic method that returns the selections you want to display like “list_farm_names.”
- Create a method that displays the selections using TTY-prompt like “print_farm_name_list.”
- Create a method that returns the selected information like “farm_selection(selection).” This will look different depending on what data you are returning and how your schema is set up. In our example, we wanted to return the farm’s website URL if one existed, a list of available products at that farm, and the quantity.