DEV Community

Christina
Christina

Posted on

Set Your CLI App Apart with TTY::Prompt

TTY::Prompt is a prompt tool for command line interface applications. Created by Piotr Murach, TTY::Prompt features an impressive lineup of prompt types for gathering user input, tools for validating said input, and can greatly improve the user experience of any CLI application. I came across this gem (literally and figuratively) when I was working on my first CLI project at Flatiron School and it elevated the user experience and look of my application.

Getting Started

To get started using TTY::Prompt, add gem ‘tty-prompt’ to your Gemfile and then execute bundle install in the terminal. Alternatively, install it via gem install tty-prompt in the terminal. Then, inside the file where you will be using TTY::Prompt, add the lines: require ‘tty-prompt’ and prompt = TTY::Prompt.new.

Usage

prompt.ask

For simple input, use ask:
prompt.ask('What is your name?', default: ENV['USER'])
# => What is your name? (christina)

You can also easily validate input:
email = prompt.ask(‘Please enter your email’) do |response|
response.validate(/\A\w+@\w.\w+Z/)
response.messages[:valid?] = ‘Invalid email address’
end

prompt.mask

Or if you want to input a password, you can use mask:
prompt.mask(‘Please enter your password: ’)
# => Please enter your password: ••••••••

prompt.select and prompt.multi-select

Perhaps one of my favorite features is select. You can use this as a menu or question with a list of options that the user can scroll through to select a single option. One of the best side-effects of this kind of menu is that you don’t have to have validations for these inputs since the user is strictly limited to the options you provide. This can significantly clean up your code and improve user experience in one fell swoop.
options = ["Write a review", "Edit a review", "Delete a review", "Back to main menu"]
prompt.select(‘Please select an option: ‘, options)
# =>
# Please select an option: (Use ↑/↓ arrow keys, press Enter to select)
# ‣ Write a review
# Edit a review
# Delete a review
# Back to main menu

Or if you want the option to select multiple items, you can use multi-select:
options = %w(rock jazz pop electronic rap)
prompt.multi-select(‘Please select your favorite genres: ‘, options)
Please select your favorite genres: (Use ↑/↓ arrow keys, press Space to select and Enter to finish)
# ‣ ⬡ rock
# ⬡ jazz
# ⬡ pop
# ⬡ electronic
# ⬡ rap

Conclusion

This post is meant to give you a small introduction to some of the neat features and benefits that TTY::Prompt can provide to bolster your CLI project. I highly recommend checking out the documentation if you decide to add this to your project, there are many more features for you to explore.

Top comments (0)