Class | HighLine::Question |
In: |
lib/highline/question.rb
|
Parent: | Object |
Question objects contain all the details of a single invocation of HighLine.ask(). The object is initialized by the parameters passed to HighLine.ask() and then queried to make sure each step of the input process is handled according to the users wishes.
above | [RW] | Used to control range checks for answer. | ||||||||||||
answer_type | [RW] | The type that will be used to convert this answer. | ||||||||||||
below | [RW] | Used to control range checks for answer. | ||||||||||||
case | [RW] | Used to control character case processing for the answer to this question. See HighLine::Question.change_case() for acceptable settings. | ||||||||||||
character | [RW] |
Can be set to true to use HighLine’s cross-platform character
reader instead of fetching an entire line of input. (Note: HighLine’s character reader ONLY
supports STDIN on Windows and Unix.) Can also be set to :getc to
use that method on the input stream.
WARNING: The echo attribute for a question is ignored when using thw :getc method. |
||||||||||||
confirm | [RW] | Asks a yes or no confirmation question, to ensure a user knows what they have just agreed to. If set to true the question will be, "Are you sure? " Any other true value for this attribute is assumed to be the question to ask. When false or nil (the default), answers are not confirmed. | ||||||||||||
default | [RW] | Used to provide a default answer to this question. | ||||||||||||
directory | [RW] | The directory from which a user will be allowed to select files, when File or Pathname is specified as an answer_type. Initially set to Pathname.new(File.expand_path(File.dirname($0))). | ||||||||||||
echo | [RW] |
Can be set to true or false to control whether or not
input will be echoed back to the user. A setting of true will
cause echo to match input, but any other true value will be treated as to
String to echo for each character typed.
This requires HighLine’s character reader. See the character attribute for details. Note: When using HighLine to manage echo on Unix based systems, we recommend installing the termios gem. Without it, it’s possible to type fast enough to have letters still show up (when reading character by character only). |
||||||||||||
first_answer | [W] | When set to a non nil value, this will be tried as an answer to the question. If this answer passes validations, it will become the result without the user ever being prompted. Otherwise this value is discarded, and this Question is resolved as a normal call to HighLine.ask(). | ||||||||||||
gather | [RW] |
When set, the user will be prompted for multiple answers which will be
collected into an Array or Hash and returned as the final answer.
You can set gather to an Integer to have an Array of exactly that many answers collected, or a String/Regexp to match an end input which will not be returned in the Array. Optionally gather can be set to a Hash. In this case, the question will be asked once for each key and the answers will be returned in a Hash, mapped by key. The @key variable is set before each question is evaluated, so you can use it in your question. |
||||||||||||
glob | [RW] | The glob pattern used to limit file selection when File or Pathname is specified as an answer_type. Initially set to "*". | ||||||||||||
in | [RW] | If set, answer must pass an include?() check on this object. | ||||||||||||
limit | [RW] |
Allows you to set a character limit for input.
WARNING: This option forces a character by character read. |
||||||||||||
question | [RW] | The ERb template of the question to be asked. | ||||||||||||
readline | [RW] |
Use the Readline library to fetch input. This allows input editing as well
as keeping a history. In addition, tab will auto-complete within an Array
of choices or a file listing.
WARNING: This option is incompatible with all of HighLine’s character reading modes and it causes HighLine to ignore the specified input stream. |
||||||||||||
responses | [R] |
A Hash that stores the various responses used by HighLine to notify the user. The currently used
responses and their purpose are as follows:
|
||||||||||||
validate | [RW] | If set to a Regexp, the answer must match (before type conversion). Can also be set to a Proc which will be called with the provided answer to validate with a true or false return. | ||||||||||||
whitespace | [RW] | Used to control whitespace processing for the answer to this question. See HighLine::Question.remove_whitespace() for acceptable settings. |
Create an instance of HighLine::Question. Expects a question to ask (can be "") and an answer_type to convert the answer to. The answer_type parameter must be a type recongnized by Question.convert(). If given, a block is yeilded the new Question object to allow custom initializaion.
# File lib/highline/question.rb, line 34 34: def initialize( question, answer_type ) 35: # initialize instance data 36: @question = question 37: @answer_type = answer_type 38: 39: @character = nil 40: @limit = nil 41: @echo = true 42: @readline = false 43: @whitespace = :strip 44: @case = nil 45: @default = nil 46: @validate = nil 47: @above = nil 48: @below = nil 49: @in = nil 50: @confirm = nil 51: @gather = false 52: @first_answer = nil 53: @directory = Pathname.new(File.expand_path(File.dirname($0))) 54: @glob = "*" 55: @responses = Hash.new 56: 57: # allow block to override settings 58: yield self if block_given? 59: 60: # finalize responses based on settings 61: build_responses 62: end
Returns the provided answer_string or the default answer for this Question if a default was set and the answer is empty.
# File lib/highline/question.rb, line 201 201: def answer_or_default( answer_string ) 202: if answer_string.length == 0 and not @default.nil? 203: @default 204: else 205: answer_string 206: end 207: end
Called late in the initialization process to build intelligent responses based on the details of this Question object.
# File lib/highline/question.rb, line 213 213: def build_responses( ) 214: ### WARNING: This code is quasi-duplicated in ### 215: ### Menu.update_responses(). Check there too when ### 216: ### making changes! ### 217: append_default unless default.nil? 218: @responses = { :ambiguous_completion => 219: "Ambiguous choice. " + 220: "Please choose one of #{@answer_type.inspect}.", 221: :ask_on_error => 222: "? ", 223: :invalid_type => 224: "You must enter a valid #{@answer_type}.", 225: :no_completion => 226: "You must choose one of " + 227: "#{@answer_type.inspect}.", 228: :not_in_range => 229: "Your answer isn't within the expected range " + 230: "(#{expected_range}).", 231: :not_valid => 232: "Your answer isn't valid (must match " + 233: "#{@validate.inspect})." }.merge(@responses) 234: ### WARNING: This code is quasi-duplicated in ### 235: ### Menu.update_responses(). Check there too when ### 236: ### making changes! ### 237: end
Returns the provided answer_string after changing character case by the rules of this Question. Valid settings for whitespace are:
nil: | Do not alter character case. (Default.) |
:up: | Calls upcase(). |
:upcase: | Calls upcase(). |
:down: | Calls downcase(). |
:downcase: | Calls downcase(). |
:capitalize: | Calls capitalize(). |
An unrecognized choice (like :none) is treated as nil.
# File lib/highline/question.rb, line 253 253: def change_case( answer_string ) 254: if [:up, :upcase].include?(@case) 255: answer_string.upcase 256: elsif [:down, :downcase].include?(@case) 257: answer_string.downcase 258: elsif @case == :capitalize 259: answer_string.capitalize 260: else 261: answer_string 262: end 263: end
Transforms the given answer_string into the expected type for this Question. Currently supported conversions are:
[…]: | Answer must be a member of the passed Array. Auto-completion is used to expand partial answers. |
lambda {…}: | Answer is passed to lambda for conversion. |
Date: | Date.parse() is called with answer. |
DateTime: | DateTime.parse() is called with answer. |
File: | The entered file name is auto-completed in terms of directory + glob, opened, and returned. |
Float: | Answer is converted with Kernel.Float(). |
Integer: | Answer is converted with Kernel.Integer(). |
nil: | Answer is left in String format. (Default.) |
Pathname: | Same as File, save that a Pathname object is returned. |
String: | Answer is converted with Kernel.String(). |
Regexp: | Answer is fed to Regexp.new(). |
Symbol: | The method to_sym() is called on answer and the result returned. |
any other Class: | The answer is passed on to Class.parse(). |
This method throws ArgumentError, if the conversion cannot be completed for any reason.
# File lib/highline/question.rb, line 293 293: def convert( answer_string ) 294: if @answer_type.nil? 295: answer_string 296: elsif [Float, Integer, String].include?(@answer_type) 297: Kernel.send(@answer_type.to_s.to_sym, answer_string) 298: elsif @answer_type == Symbol 299: answer_string.to_sym 300: elsif @answer_type == Regexp 301: Regexp.new(answer_string) 302: elsif @answer_type.is_a?(Array) or [File, Pathname].include?(@answer_type) 303: # cheating, using OptionParser's Completion module 304: choices = selection 305: choices.extend(OptionParser::Completion) 306: answer = choices.complete(answer_string) 307: if answer.nil? 308: raise NoAutoCompleteMatch 309: end 310: if @answer_type.is_a?(Array) 311: answer.last 312: elsif @answer_type == File 313: File.open(File.join(@directory.to_s, answer.last)) 314: else 315: Pathname.new(File.join(@directory.to_s, answer.last)) 316: end 317: elsif [Date, DateTime].include?(@answer_type) or @answer_type.is_a?(Class) 318: @answer_type.parse(answer_string) 319: elsif @answer_type.is_a?(Proc) 320: @answer_type[answer_string] 321: end 322: end
Returns a english explination of the current range settings.
# File lib/highline/question.rb, line 325 325: def expected_range( ) 326: expected = [ ] 327: 328: expected << "above #{@above}" unless @above.nil? 329: expected << "below #{@below}" unless @below.nil? 330: expected << "included in #{@in.inspect}" unless @in.nil? 331: 332: case expected.size 333: when 0 then "" 334: when 1 then expected.first 335: when 2 then expected.join(" and ") 336: else expected[0..-2].join(", ") + ", and #{expected.last}" 337: end 338: end
Returns first_answer, which will be unset following this call.
# File lib/highline/question.rb, line 341 341: def first_answer( ) 342: @first_answer 343: ensure 344: @first_answer = nil 345: end
Returns true if first_answer is set.
# File lib/highline/question.rb, line 348 348: def first_answer?( ) 349: not @first_answer.nil? 350: end
Returns true if the answer_object is greater than the above attribute, less than the below attribute and included?()ed in the in attribute. Otherwise, false is returned. Any nil attributes are not checked.
# File lib/highline/question.rb, line 358 358: def in_range?( answer_object ) 359: (@above.nil? or answer_object > @above) and 360: (@below.nil? or answer_object < @below) and 361: (@in.nil? or @in.include?(answer_object)) 362: end
Returns the provided answer_string after processing whitespace by the rules of this Question. Valid settings for whitespace are:
nil: | Do not alter whitespace. |
:strip: | Calls strip(). (Default.) |
:chomp: | Calls chomp(). |
:collapse: | Collapses all whitspace runs to a single space. |
:strip_and_collapse: | Calls strip(), then collapses all whitspace runs to a single space. |
:chomp_and_collapse: | Calls chomp(), then collapses all whitspace runs to a single space. |
:remove: | Removes all whitespace. |
An unrecognized choice (like :none) is treated as nil.
This process is skipped, for single character input.
# File lib/highline/question.rb, line 383 383: def remove_whitespace( answer_string ) 384: if @whitespace.nil? 385: answer_string 386: elsif [:strip, :chomp].include?(@whitespace) 387: answer_string.send(@whitespace) 388: elsif @whitespace == :collapse 389: answer_string.gsub(/\s+/, " ") 390: elsif [:strip_and_collapse, :chomp_and_collapse].include?(@whitespace) 391: result = answer_string.send(@whitespace.to_s[/^[a-z]+/]) 392: result.gsub(/\s+/, " ") 393: elsif @whitespace == :remove 394: answer_string.gsub(/\s+/, "") 395: else 396: answer_string 397: end 398: end
Returns an Array of valid answers to this question. These answers are only known when answer_type is set to an Array of choices, File, or Pathname. Any other time, this method will return an empty Array.
# File lib/highline/question.rb, line 405 405: def selection( ) 406: if @answer_type.is_a?(Array) 407: @answer_type 408: elsif [File, Pathname].include?(@answer_type) 409: Dir[File.join(@directory.to_s, @glob)].map do |file| 410: File.basename(file) 411: end 412: else 413: [ ] 414: end 415: end
Stringifies the question to be asked.
# File lib/highline/question.rb, line 418 418: def to_str( ) 419: @question 420: end
Returns true if the provided answer_string is accepted by the validate attribute or false if it’s not.
It’s important to realize that an answer is validated after whitespace and case handling.
# File lib/highline/question.rb, line 429 429: def valid_answer?( answer_string ) 430: @validate.nil? or 431: (@validate.is_a?(Regexp) and answer_string =~ @validate) or 432: (@validate.is_a?(Proc) and @validate[answer_string]) 433: end
Adds the default choice to the end of question between |…|. Trailing whitespace is preserved so the function of HighLine.say() is not affected.
# File lib/highline/question.rb, line 442 442: def append_default( ) 443: if @question =~ /([\t ]+)\Z/ 444: @question << "|#{@default}|#{$1}" 445: elsif @question == "" 446: @question << "|#{@default}| " 447: elsif @question[-1, 1] == "\n" 448: @question[-2, 0] = " |#{@default}|" 449: else 450: @question << " |#{@default}|" 451: end 452: end