Class: Samovar::Output::UsageFormatter
- Inherits:
-
Object
- Object
- Samovar::Output::UsageFormatter
- Defined in:
- lib/samovar/output/usage_formatter.rb
Overview
Formats and prints usage information to a terminal.
Dispatches on the type of each output object to apply custom formatting rules.
Class Method Summary collapse
-
.print(rows, output) {|formatter| ... } ⇒ Object
Print usage information to the output.
Instance Method Summary collapse
-
#initialize(output) ⇒ UsageFormatter
constructor
Initialize a new usage formatter.
-
#map(object, *arguments, first: true) ⇒ Object
Format and print the given object according to its type.
-
#print(rows, first: true) ⇒ Object
Print the formatted usage output.
Constructor Details
#initialize(output) ⇒ UsageFormatter
Initialize a new usage formatter.
39 40 41 42 43 44 45 46 47 |
# File 'lib/samovar/output/usage_formatter.rb', line 39 def initialize(output) @output = output @width = 80 @terminal = Console::Terminal.for(@output) @terminal[:header] = @terminal.style(nil, nil, :bright) @terminal[:description] = @terminal.style(:blue) @terminal[:error] = @terminal.style(:red) end |
Class Method Details
.print(rows, output) {|formatter| ... } ⇒ Object
Print usage information to the output.
27 28 29 30 31 32 33 |
# File 'lib/samovar/output/usage_formatter.rb', line 27 def self.print(rows, output) formatter = self.new(output) yield formatter if block_given? formatter.print(rows) end |
Instance Method Details
#map(object, *arguments, first: true) ⇒ Object
Format and print the given object according to its type.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/samovar/output/usage_formatter.rb', line 53 def map(object, *arguments, first: true) case object when InvalidInputError # This is a little hack which avoids printing out "--help" if it was part of an incomplete parse. In the future I'd prefer if this was handled explicitly. @terminal.puts("#{object.} in:", style: :error) unless object.help? when MissingValueError @terminal.puts("#{object.} in:", style: :error) when Header header, rows = object, arguments.first if first first = false else @terminal.puts end command_line = header.object.command_line(header.name) @terminal.puts "#{rows.indentation}#{command_line}", style: :header if description = header.object.description @terminal.puts "#{rows.indentation}\t#{description}", style: :description @terminal.puts end when Row row, rows = object, arguments.first @terminal.puts "#{rows.indentation}#{row.align(rows.columns)}" when Rows object.each do |row, rows| first = map(row, rows, first: first) end else raise ArgumentError, "Unable to format #{object.class}!" end return first end |
#print(rows, first: true) ⇒ Object
Print the formatted usage output.
91 92 93 |
# File 'lib/samovar/output/usage_formatter.rb', line 91 def print(rows, first: true) map(rows, first: first) end |