Class: LilUtils::CLI::OptionList
- Inherits:
-
Object
- Object
- LilUtils::CLI::OptionList
- Defined in:
- lib/lilutils/cli/cli.rb
Overview
Models a generic list of options that determines if a particular key results in valid response. Takes care of generic behavior (display, validity of user response, defaults) when a list of options is presented to the user.
Direct Known Subclasses
Constant Summary collapse
- DEFAULT_PROMPT =
"Do you want to proceed?"
Instance Method Summary collapse
- #debug(str) ⇒ Object
-
#display_string ⇒ Object
subclasses may override, but don’t have to.
-
#initialize(options, default_option_index, prompt, strict, istream = $stdin, ostream = $stdout) ⇒ OptionList
constructor
A new instance of OptionList.
-
#show ⇒ Object
the whole point is subclasses get this for free.
- #valid_response?(r) ⇒ Boolean
Constructor Details
#initialize(options, default_option_index, prompt, strict, istream = $stdin, ostream = $stdout) ⇒ OptionList
Returns a new instance of OptionList.
127 128 129 130 131 132 133 134 135 |
# File 'lib/lilutils/cli/cli.rb', line 127 def initialize(, default_option_index, prompt, strict, istream=$stdin, ostream=$stdout) # check, list must be non-nil and must have at least two elements @options = @default_option = [default_option_index] @prompt = prompt @strict = strict @istream = istream @ostream = ostream end |
Instance Method Details
#debug(str) ⇒ Object
176 177 178 |
# File 'lib/lilutils/cli/cli.rb', line 176 def debug(str) puts "debug: #{str}" if $DEBUG end |
#display_string ⇒ Object
subclasses may override, but don’t have to
146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/lilutils/cli/cli.rb', line 146 def display_string long_str = "" @options.each_with_index do |option, index| if option == @default_option long_str << option.as_default else long_str << option.as_non_default end long_str << "/" if index < (@options.size-1) end "#{@prompt} [#{long_str}] " end |
#show ⇒ Object
the whole point is subclasses get this for free
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/lilutils/cli/cli.rb', line 160 def show @ostream.print "#{display_string}" response = @istream.gets.chomp! chosen = valid_response? response if @strict until chosen @ostream.print "\nSorry, I don't understand #{response}, #{display_string}" response = @istream.gets.chomp! chosen = valid_response? response end else chosen = @default_option # when not strict, any key => default option end chosen end |
#valid_response?(r) ⇒ Boolean
137 138 139 140 141 142 143 |
# File 'lib/lilutils/cli/cli.rb', line 137 def valid_response?(r) @options.each do |option| debug "#{option} == #{@default_option} ? : (#{option == @default_option})" return option if (option == @default_option && r == "") || (option.valid_response(r)) end nil end |