Class: EasyPrompt
- Inherits:
-
Object
- Object
- EasyPrompt
- Defined in:
- lib/easyprompt.rb
Defined Under Namespace
Classes: MockCommandLineUser, MockableStdin, MockableStdout
Constant Summary collapse
- Version =
'0.1.2'
Instance Method Summary collapse
-
#ask(msg, default = nil, response_class = :string) ⇒ Object
Asks the user for input.
-
#initialize ⇒ EasyPrompt
constructor
A new instance of EasyPrompt.
-
#prompt(msg, default = nil, response_class = :string) ⇒ Object
:nodoc:.
Constructor Details
#initialize ⇒ EasyPrompt
Returns a new instance of EasyPrompt.
29 |
# File 'lib/easyprompt.rb', line 29 def initialize; @stdout = MockableStdout.get_mockable_stdout; end |
Instance Method Details
#ask(msg, default = nil, response_class = :string) ⇒ Object
Asks the user for input.
- msg
-
The prompt that tells the user what information to enter next.
- default
-
The default value that will be returned if the user enters a newline (usually by pressing “Enter”) without typing any information. The default value will be displayed in square brackets after
msg
. - response_class
-
The sort of value that EasyPrompt#ask should return. Valid response classes are:
- :string
-
This is the default.
- :boolean
-
Values will be turned into
true
orfalse
depending on whether the user enters “y” or “n”. - :regexp
-
Values will be read as a regular expression source. If the user enters an invalid regexp source, EasyPrompt will re-prompt until a valid regexp source is entered.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/easyprompt.rb', line 38 def ask( msg, default = nil, response_class = :string ) success = false last_error = nil until success success = true full_msg = msg full_msg = last_error + ' ' + full_msg if last_error @stdout.write( prompt( full_msg, default, response_class ) + ' ' ) stdin = MockableStdin.get_mockable_stdin response = stdin.gets response.chomp! if response == '' response = default else if response_class == :boolean response = response =~ /^y/i elsif response_class == :regexp begin response = Regexp.new response rescue RegexpError success = false last_error = "I'm sorry, but that was not a valid regular expression." end end end end response end |
#prompt(msg, default = nil, response_class = :string) ⇒ Object
:nodoc:
67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/easyprompt.rb', line 67 def prompt( msg, default = nil, response_class = :string ) #:nodoc: prompt = msg unless default.nil? if response_class == :boolean default_str = default ? 'y' : 'n' elsif response_class == :regexp default_str = default.source else default_str = default.to_s end prompt += " [#{ default_str }]" end prompt end |