class Perfume::Console
Public: Sometimes there’s a need to ask user a question or to get stuff from him. This simple class handles this. You can initialize this virtual “Console” pointed to given input and output stream and perform common operations like getting user input, asking questions (yes/no questions too), etc.
Public Instance Methods
Public: Asks user a question. As with read_user_input
, the answer can be obtained from both, return value and yielded argument.
Example
console = Console.new console.ask("How much do you know?") do |answer| puts "So you know #{answer}" end $ How much do you know?: nothing $ So you know nothing...
# File lib/perfume/console.rb, line 35 def ask(question, &block) @output.write(question + ': ') read_user_input(&block) end
Public: Same like ask
, but converts the answer to boolean value. It also formats the question a little bit to indicate that we’re asking about the boolean. Any other answer than case insensitive “y” or “yes” will be converted to false.
Example
console = Console.new console.ask("Are you Jon Snow?") do |answer| puts "Answer: #{answer.inspect}" end $ Are you Jon Snow? [y/N]: Yes $ Answer: true
# File lib/perfume/console.rb, line 54 def ask_yes_or_no(question, &block) ask(question + ' [y/N]') do |answer| %[y yes].include?(answer.downcase).tap do |bool_answer| yield bool_answer if block_given? end end end
# File lib/perfume/console.rb, line 11 def defaults { input: STDIN, output: STDOUT } end
Public: Reads user input from given input stream. The answer can be either obtained from result or yielded value.
# File lib/perfume/console.rb, line 17 def read_user_input(&block) value = @input.gets.to_s.strip block_given? ? block.call(value) : value end