| Class | HighLine |
| In: |
lib/highline/color_scheme.rb
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.5.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. | |
| ERASE_LINE | = | "\e[K" | Erase the current line of terminal output. | |
| ERASE_CHAR | = | "\e[P" | Erase the character under the cursor. | |
| 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. |
Pass ColorScheme to setting to turn set a HighLine color scheme.
# File lib/highline.rb, line 71 def self.color_scheme=( setting ) @@color_scheme = setting end
Create an instance of HighLine, connected to the streams input and output.
# File lib/highline.rb, line 149 def initialize( input = $stdin, output = $stdout, wrap_at = nil, page_at = nil ) @input = input @output = output self.wrap_at = wrap_at self.page_at = page_at @question = nil @answer = nil @menu = nil @header = nil @prompt = nil @gather = nil @answers = nil @key = nil 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. A block can be provided to further configure the question as in HighLine.ask()
Raises EOFError if input is exhausted.
# File lib/highline.rb, line 183 def agree( yes_or_no_question, character = nil ) ask(yes_or_no_question, lambda { |yn| yn.downcase[0] == ?y}) do |q| q.validate = /\Ay(?:es)?|no?\Z/i q.responses[:not_valid] = 'Please enter "yes" or "no".' q.responses[:ask_on_error] = :question q.character = character yield q if block_given? end 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 208 def ask( question, answer_type = String, &details ) # :yields: question @question ||= Question.new(question, answer_type, &details) return gather if @question.gather # readline() needs to handle it's own output, but readline only supports # full line reading. Therefore if @question.echo is anything but true, # the prompt will not be issued. And we have to account for that now. say(@question) unless (@question.readline and @question.echo == true) begin @answer = @question.answer_or_default(get_response) unless @question.valid_answer?(@answer) explain_error(:not_valid) raise QuestionError end @answer = @question.convert(@answer) if @question.in_range?(@answer) if @question.confirm # need to add a layer of scope to ask a question inside a # question, without destroying instance data context_change = self.class.new(@input, @output, @wrap_at, @page_at) if @question.confirm == true confirm_question = "Are you sure? " else # evaluate ERb under initial scope, so it will have # access to @question and @answer template = ERB.new(@question.confirm, nil, "%") confirm_question = template.result(binding) end unless context_change.agree(confirm_question) explain_error(nil) raise QuestionError end end @answer else explain_error(:not_in_range) raise QuestionError end rescue QuestionError retry rescue ArgumentError, NameError => error raise if error.is_a?(NoMethodError) if error.message =~ /ambiguous/ # the assumption here is that OptionParser::Completion#complete # (used for ambiguity resolution) throws exceptions containing # the word 'ambiguous' whenever resolution fails explain_error(:ambiguous_completion) else explain_error(:invalid_type) end retry rescue Question::NoAutoCompleteMatch explain_error(:no_completion) retry ensure @question = nil # Reset Question object. end 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 286 def choose( *items, &details ) @menu = @question = Menu.new(&details) @menu.choices(*items) unless items.empty? # Set _answer_type_ so we can double as the Question for ask(). @menu.answer_type = if @menu.shell lambda do |command| # shell-style selection first_word = command.to_s.split.first || "" options = @menu.options options.extend(OptionParser::Completion) answer = options.complete(first_word) if answer.nil? raise Question::NoAutoCompleteMatch end [answer.last, command.sub(/^\s*#{first_word}\s*/, "")] end else @menu.options # normal menu selection, by index or name end # Provide hooks for ERb layouts. @header = @menu.header @prompt = @menu.prompt if @menu.shell selected = ask("Ignored", @menu.answer_type) @menu.select(self, *selected) else selected = ask("Ignored", @menu.answer_type) @menu.select(self, selected) end 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 333 def color( string, *colors ) return string unless self.class.use_color? colors.map! do |c| if self.class.using_color_scheme? and self.class.color_scheme.include? c self.class.color_scheme[c] elsif c.is_a? Symbol self.class.const_get(c.to_s.upcase) else c end end "#{colors.flatten.join}#{string}#{CLEAR}" 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 376 def list( items, mode = :rows, option = nil ) items = items.to_ary.map do |item| ERB.new(item, nil, "%").result(binding) end case mode when :inline option = " or " if option.nil? case items.size when 0 "" when 1 items.first when 2 "#{items.first}#{option}#{items.last}" else items[0..-2].join(", ") + "#{option}#{items.last}" end when :columns_across, :columns_down max_length = actual_length( items.max { |a, b| actual_length(a) <=> actual_length(b) } ) if option.nil? limit = @wrap_at || 80 option = (limit + 2) / (max_length + 2) end items = items.map do |item| pad = max_length + (item.length - actual_length(item)) "%-#{pad}s" % item end row_count = (items.size / option.to_f).ceil if mode == :columns_across rows = Array.new(row_count) { Array.new } items.each_with_index do |item, index| rows[index / option] << item end rows.map { |row| row.join(" ") + "\n" }.join else columns = Array.new(option) { Array.new } items.each_with_index do |item, index| columns[index / row_count] << item end list = "" columns.first.size.times do |index| list << columns.map { |column| column[index] }. compact.join(" ") + "\n" end list end else items.map { |i| "#{i}\n" }.join end end
Returns the number of columns for the console, or a default it they cannot be determined.
# File lib/highline.rb, line 488 def output_cols return 80 unless @output.tty? terminal_size.first rescue return 80 end
Returns the number of rows for the console, or a default if they cannot be determined.
# File lib/highline.rb, line 499 def output_rows return 24 unless @output.tty? terminal_size.last rescue return 24 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 480 def page_at=( setting ) @page_at = setting == :auto ? output_rows : setting 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 446 def say( statement ) statement = statement.to_str return unless statement.length > 0 template = ERB.new(statement, nil, "%") statement = template.result(binding) statement = wrap(statement) unless @wrap_at.nil? statement = page_print(statement) unless @page_at.nil? if statement[-1, 1] == " " or statement[-1, 1] == "\t" @output.print(statement) @output.flush else @output.puts(statement) end 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 470 def wrap_at=( setting ) @wrap_at = setting == :auto ? output_cols : setting end