Class | HighLine |
In: |
lib/highline/menu.rb
lib/highline/question.rb lib/highline/system_extensions.rb lib/highline.rb |
Parent: | Object |
A HighLine object is a "high-level line oriented" shell over an input and an output stream. HighLine simplifies common console interaction, effectively replacing puts() and gets(). User code can simply specify the question to ask and any details about user interaction, then leave the rest of the work to HighLine. When HighLine.ask() returns, you’ll have the answer you requested, even if HighLine had to ask many times, validate results, perform range checking, convert types, etc.
VERSION | = | "1.2.2".freeze | The version of the installed library. | |
CLEAR | = | "\e[0m" | Embed in a String to clear all previous ANSI sequences. This MUST be done before the program exits! | |
RESET | = | CLEAR | An alias for CLEAR. | |
BOLD | = | "\e[1m" | The start of an ANSI bold sequence. | |
DARK | = | "\e[2m" | The start of an ANSI dark sequence. (Terminal support uncommon.) | |
UNDERLINE | = | "\e[4m" | The start of an ANSI underline sequence. | |
UNDERSCORE | = | UNDERLINE | An alias for UNDERLINE. | |
BLINK | = | "\e[5m" | The start of an ANSI blink sequence. (Terminal support uncommon.) | |
REVERSE | = | "\e[7m" | The start of an ANSI reverse sequence. | |
CONCEALED | = | "\e[8m" | The start of an ANSI concealed sequence. (Terminal support uncommon.) | |
BLACK | = | "\e[30m" | Set the terminal’s foreground ANSI color to black. | |
RED | = | "\e[31m" | Set the terminal’s foreground ANSI color to red. | |
GREEN | = | "\e[32m" | Set the terminal’s foreground ANSI color to green. | |
YELLOW | = | "\e[33m" | Set the terminal’s foreground ANSI color to yellow. | |
BLUE | = | "\e[34m" | Set the terminal’s foreground ANSI color to blue. | |
MAGENTA | = | "\e[35m" | Set the terminal’s foreground ANSI color to magenta. | |
CYAN | = | "\e[36m" | Set the terminal’s foreground ANSI color to cyan. | |
WHITE | = | "\e[37m" | Set the terminal’s foreground ANSI color to white. | |
ON_BLACK | = | "\e[40m" | Set the terminal’s background ANSI color to black. | |
ON_RED | = | "\e[41m" | Set the terminal’s background ANSI color to red. | |
ON_GREEN | = | "\e[42m" | Set the terminal’s background ANSI color to green. | |
ON_YELLOW | = | "\e[43m" | Set the terminal’s background ANSI color to yellow. | |
ON_BLUE | = | "\e[44m" | Set the terminal’s background ANSI color to blue. | |
ON_MAGENTA | = | "\e[45m" | Set the terminal’s background ANSI color to magenta. | |
ON_CYAN | = | "\e[46m" | Set the terminal’s background ANSI color to cyan. | |
ON_WHITE | = | "\e[47m" | Set the terminal’s background ANSI color to white. |
page_at | [R] | The current row setting for paging output. |
wrap_at | [R] | The current column setting for wrapping output. |
Create an instance of HighLine, connected to the streams input and output.
# File lib/highline.rb, line 111 111: def initialize( input = $stdin, output = $stdout, 112: wrap_at = nil, page_at = nil ) 113: @input = input 114: @output = output 115: 116: self.wrap_at = wrap_at 117: self.page_at = page_at 118: 119: @question = nil 120: @answer = nil 121: @menu = nil 122: @header = nil 123: @prompt = nil 124: @gather = nil 125: @answers = nil 126: @key = nil 127: end
A shortcut to HighLine.ask() a question that only accepts "yes" or "no" answers ("y" and "n" are allowed) and returns true or false (true for "yes"). If provided a true value, character will cause HighLine to fetch a single character response.
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 144 144: def agree( yes_or_no_question, character = nil ) 145: ask(yes_or_no_question, lambda { |yn| yn.downcase[0] == ?y}) do |q| 146: q.validate = /\Ay(?:es)?|no?\Z/i 147: q.responses[:not_valid] = 'Please enter "yes" or "no".' 148: q.responses[:ask_on_error] = :question 149: q.character = character 150: end 151: end
This method is the primary interface for user input. Just provide a question to ask the user, the answer_type you want returned, and optionally a code block setting up details of how you want the question handled. See HighLine.say() for details on the format of question, and HighLine::Question for more information about answer_type and what’s valid in the code block.
If @question is set before ask() is called, parameters are ignored and that object (must be a HighLine::Question) is used to drive the process instead.
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 167 167: def ask( question, answer_type = String, &details ) # :yields: question 168: @question ||= Question.new(question, answer_type, &details) 169: 170: return gather if @question.gather 171: 172: # readline() needs to handle it's own output 173: say(@question) unless @question.readline 174: begin 175: @answer = @question.answer_or_default(get_response) 176: unless @question.valid_answer?(@answer) 177: explain_error(:not_valid) 178: raise QuestionError 179: end 180: 181: @answer = @question.convert(@answer) 182: 183: if @question.in_range?(@answer) 184: if @question.confirm 185: # need to add a layer of scope to ask a question inside a 186: # question, without destroying instance data 187: context_change = self.class.new(@input, @output, @wrap_at, @page_at) 188: if @question.confirm == true 189: confirm_question = "Are you sure? " 190: else 191: # evaluate ERb under initial scope, so it will have 192: # access to @question and @answer 193: template = ERB.new(@question.confirm, nil, "%") 194: confirm_question = template.result(binding) 195: end 196: unless context_change.agree(confirm_question) 197: explain_error(nil) 198: raise QuestionError 199: end 200: end 201: 202: @answer 203: else 204: explain_error(:not_in_range) 205: raise QuestionError 206: end 207: rescue QuestionError 208: retry 209: rescue ArgumentError 210: explain_error(:invalid_type) 211: retry 212: rescue Question::NoAutoCompleteMatch 213: explain_error(:no_completion) 214: retry 215: rescue NameError 216: raise if $!.is_a?(NoMethodError) 217: explain_error(:ambiguous_completion) 218: retry 219: ensure 220: @question = nil # Reset Question object. 221: end 222: end
This method is HighLine’s menu handler. For simple usage, you can just pass all the menu items you wish to display. At that point, choose() will build and display a menu, walk the user through selection, and return their choice amoung the provided items. You might use this in a case statement for quick and dirty menus.
However, choose() is capable of much more. If provided, a block will be passed a HighLine::Menu object to configure. Using this method, you can customize all the details of menu handling from index display, to building a complete shell-like menuing system. See HighLine::Menu for all the methods it responds to.
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 239 239: def choose( *items, &details ) 240: @menu = @question = Menu.new(&details) 241: @menu.choices(*items) unless items.empty? 242: 243: # Set _answer_type_ so we can double as the Question for ask(). 244: @menu.answer_type = if @menu.shell 245: lambda do |command| # shell-style selection 246: first_word = command.split.first 247: 248: options = @menu.options 249: options.extend(OptionParser::Completion) 250: answer = options.complete(first_word) 251: 252: if answer.nil? 253: raise Question::NoAutoCompleteMatch 254: end 255: 256: [answer.last, command.sub(/^\s*#{first_word}\s*/, "")] 257: end 258: else 259: @menu.options # normal menu selection, by index or name 260: end 261: 262: # Provide hooks for ERb layouts. 263: @header = @menu.header 264: @prompt = @menu.prompt 265: 266: if @menu.shell 267: selected = ask("Ignored", @menu.answer_type) 268: @menu.select(self, *selected) 269: else 270: selected = ask("Ignored", @menu.answer_type) 271: @menu.select(self, selected) 272: end 273: end
This method provides easy access to ANSI color sequences, without the user needing to remember to CLEAR at the end of each sequence. Just pass the string to color, followed by a list of colors you would like it to be affected by. The colors can be HighLine class constants, or symbols (:blue for BLUE, for example). A CLEAR will automatically be embedded to the end of the returned String.
This method returns the original string unchanged if HighLine::use_color? is false.
# File lib/highline.rb, line 286 286: def color( string, *colors ) 287: return string unless self.class.use_color? 288: 289: colors.map! do |c| 290: if c.is_a?(Symbol) 291: self.class.const_get(c.to_s.upcase) 292: else 293: c 294: end 295: end 296: "#{colors.join}#{string}#{CLEAR}" 297: end
This method is a utility for quickly and easily laying out lists. It can be accessed within ERb replacements of any text that will be sent to the user.
The only required parameter is items, which should be the Array of items to list. A specified mode controls how that list is formed and option has different effects, depending on the mode. Recognized modes are:
:columns_across: | items will be placed in columns, flowing from left to right. If given, option is the number of columns to be used. When absent, columns will be determined based on wrap_at or a default of 80 characters. |
:columns_down: | Identical to :columns_across, save flow goes down. |
:inline: | All items are placed on a single line. The last two items are separated by option or a default of " or ". All other items are separated by ", ". |
:rows: | The default mode. Each of the items is placed on it’s own line. The option parameter is ignored in this mode. |
Each member of the items Array is passed through ERb and thus can contain their own expansions. Color escape expansions do not contribute to the final field width.
# File lib/highline.rb, line 327 327: def list( items, mode = :rows, option = nil ) 328: items = items.to_ary.map do |item| 329: ERB.new(item, nil, "%").result(binding) 330: end 331: 332: case mode 333: when :inline 334: option = " or " if option.nil? 335: 336: case items.size 337: when 0 338: "" 339: when 1 340: items.first 341: when 2 342: "#{items.first}#{option}#{items.last}" 343: else 344: items[0..-2].join(", ") + "#{option}#{items.last}" 345: end 346: when :columns_across, :columns_down 347: max_length = actual_length( 348: items.max { |a, b| actual_length(a) <=> actual_length(b) } 349: ) 350: 351: if option.nil? 352: limit = @wrap_at || 80 353: option = (limit + 2) / (max_length + 2) 354: end 355: 356: items = items.map do |item| 357: pad = max_length + (item.length - actual_length(item)) 358: "%-#{pad}s" % item 359: end 360: row_count = (items.size / option.to_f).ceil 361: 362: if mode == :columns_across 363: rows = Array.new(row_count) { Array.new } 364: items.each_with_index do |item, index| 365: rows[index / option] << item 366: end 367: 368: rows.map { |row| row.join(" ") + "\n" }.join 369: else 370: columns = Array.new(option) { Array.new } 371: items.each_with_index do |item, index| 372: columns[index / row_count] << item 373: end 374: 375: list = "" 376: columns.first.size.times do |index| 377: list << columns.map { |column| column[index] }. 378: compact.join(" ") + "\n" 379: end 380: list 381: end 382: else 383: items.map { |i| "#{i}\n" }.join 384: end 385: end
Returns the number of columns for the console, or a default it they cannot be determined.
# File lib/highline.rb, line 439 439: def output_cols 440: return 80 unless @output.tty? 441: terminal_size.first 442: rescue 443: return 80 444: end
Returns the number of rows for the console, or a default if they cannot be determined.
# File lib/highline.rb, line 450 450: def output_rows 451: return 24 unless @output.tty? 452: terminal_size.last 453: rescue 454: return 24 455: end
Set to an integer value to cause HighLine to page output lines over the indicated line limit. When nil, the default, no paging occurs. If set to :auto, HighLine will attempt to determing the rows available for the @output or use a sensible default.
# File lib/highline.rb, line 431 431: def page_at=( setting ) 432: @page_at = setting == :auto ? output_rows : setting 433: end
The basic output method for HighLine objects. If the provided statement ends with a space or tab character, a newline will not be appended (output will be flush()ed). All other cases are passed straight to Kernel.puts().
The statement parameter is processed as an ERb template, supporting embedded Ruby code. The template is evaluated with a binding inside the HighLine instance, providing easy access to the ANSI color constants and the HighLine.color() method.
# File lib/highline.rb, line 397 397: def say( statement ) 398: statement = statement.to_str 399: return unless statement.length > 0 400: 401: template = ERB.new(statement, nil, "%") 402: statement = template.result(binding) 403: 404: statement = wrap(statement) unless @wrap_at.nil? 405: statement = page_print(statement) unless @page_at.nil? 406: 407: if statement[-1, 1] == " " or statement[-1, 1] == "\t" 408: @output.print(statement) 409: @output.flush 410: else 411: @output.puts(statement) 412: end 413: end
Set to an integer value to cause HighLine to wrap output lines at the indicated character limit. When nil, the default, no wrapping occurs. If set to :auto, HighLine will attempt to determing the columns available for the @output or use a sensible default.
# File lib/highline.rb, line 421 421: def wrap_at=( setting ) 422: @wrap_at = setting == :auto ? output_cols : setting 423: end
Returns the length of the passed string_with_escapes, minus and color sequence escapes.
# File lib/highline.rb, line 668 668: def actual_length( string_with_escapes ) 669: string_with_escapes.gsub(/\e\[\d{1,2}m/, "").length 670: end
Ask user if they wish to continue paging output. Allows them to type "q" to cancel the paging process.
# File lib/highline.rb, line 633 633: def continue_paging? 634: command = HighLine.new(@input, @output).ask( 635: "-- press enter/return to continue or q to stop -- " 636: ) { |q| q.character = true } 637: command !~ /\A[qQ]\Z/ # Only continue paging if Q was not hit. 638: end
A helper method for sending the output stream and error and repeat of the question.
# File lib/highline.rb, line 463 463: def explain_error( error ) 464: say(@question.responses[error]) unless error.nil? 465: if @question.responses[:ask_on_error] == :question 466: say(@question) 467: elsif @question.responses[:ask_on_error] 468: say(@question.responses[:ask_on_error]) 469: end 470: end
Collects an Array/Hash full of answers as described in HighLine::Question.gather().
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 478 478: def gather( ) 479: @gather = @question.gather 480: @answers = [ ] 481: original_question = @question 482: 483: @question.gather = false 484: 485: case @gather 486: when Integer 487: @answers << ask(@question) 488: @gather -= 1 489: 490: original_question.question = "" 491: until @gather.zero? 492: @question = original_question 493: @answers << ask(@question) 494: @gather -= 1 495: end 496: when String, Regexp 497: @answers << ask(@question) 498: 499: original_question.question = "" 500: until (@gather.is_a?(String) and @answers.last.to_s == @gather) or 501: (@gather.is_a?(Regexp) and @answers.last.to_s =~ @gather) 502: @question = original_question 503: @answers << ask(@question) 504: end 505: 506: @answers.pop 507: when Hash 508: @answers = { } 509: @gather.keys.sort.each do |key| 510: @question = original_question 511: @key = key 512: @answers[key] = ask(@question) 513: end 514: end 515: 516: @answers 517: end
Read a line of input from the input stream and process whitespace as requested by the Question object.
If Question’s readline property is set, that library will be used to fetch input. WARNING: This ignores the currently set input stream.
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 528 528: def get_line( ) 529: if @question.readline 530: require "readline" # load only if needed 531: 532: # capture say()'s work in a String to feed to readline() 533: old_output = @output 534: @output = StringIO.new 535: say(@question) 536: question = @output.string 537: @output = old_output 538: 539: # prep auto-completion 540: completions = @question.selection.abbrev 541: Readline.completion_proc = lambda { |string| completions[string] } 542: 543: # work-around ugly readline() warnings 544: old_verbose = $VERBOSE 545: $VERBOSE = nil 546: answer = @question.change_case( 547: @question.remove_whitespace( 548: Readline.readline(question, true) ) ) 549: $VERBOSE = old_verbose 550: 551: answer 552: else 553: raise EOFError, "The input stream is exhausted." if @input.eof? 554: 555: @question.change_case(@question.remove_whitespace(@input.gets)) 556: end 557: end
Return a line or character of input, as requested for this question. Character input will be returned as a single character String, not an Integer.
This question’s first_answer will be returned instead of input, if set.
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 568 568: def get_response( ) 569: return @question.first_answer if @question.first_answer? 570: 571: if @question.character.nil? 572: if @question.echo == true and @question.limit.nil? 573: get_line 574: else 575: raw_no_echo_mode if stty = CHARACTER_MODE == "stty" 576: 577: line = "" 578: begin 579: while character = (stty ? @input.getc : get_character(@input)) 580: line << character.chr 581: # looking for carriage return (decimal 13) or 582: # newline (decimal 10) in raw input 583: break if character == 13 or character == 10 or 584: (@question.limit and line.size == @question.limit) 585: @output.print(@question.echo) if @question.echo != false 586: end 587: say("\n") 588: ensure 589: restore_mode if stty 590: end 591: 592: @question.change_case(@question.remove_whitespace(line)) 593: end 594: elsif @question.character == :getc 595: @question.change_case(@input.getc.chr) 596: else 597: response = get_character(@input).chr 598: echo = if @question.echo == true 599: response 600: elsif @question.echo != false 601: @question.echo 602: else 603: "" 604: end 605: say("#{echo}\n") 606: @question.change_case(response) 607: end 608: end
Page print a series of at most page_at lines for output. After each page is printed, HighLine will pause until the user presses enter/return then display the next page of data.
Note that the final page of output is not printed, but returned instead. This is to support any special handling for the final sequence.
# File lib/highline.rb, line 618 618: def page_print( output ) 619: lines = output.scan(/[^\n]*\n?/) 620: while lines.size > @page_at 621: @output.puts lines.slice!(0...@page_at).join 622: @output.puts 623: # Return last line if user wants to abort paging 624: return (["...\n"] + lines.slice(-2,1)).join unless continue_paging? 625: end 626: return lines.join 627: end
Wrap a sequence of lines at wrap_at characters per line. Existing newlines will not be affected by this process, but additional newlines may be added.
# File lib/highline.rb, line 645 645: def wrap( lines ) 646: wrapped = [ ] 647: lines.each do |line| 648: while line =~ /([^\n]{#{@wrap_at + 1},})/ 649: search = $1.dup 650: replace = $1.dup 651: if index = replace.rindex(" ", @wrap_at) 652: replace[index, 1] = "\n" 653: replace.sub!(/\n[ \t]+/, "\n") 654: line.sub!(search, replace) 655: else 656: line[@wrap_at, 0] = "\n" 657: end 658: end 659: wrapped << line 660: end 661: return wrapped.join 662: end