Class: Commando
- Inherits:
-
Object
- Object
- Commando
- Defined in:
- lib/commando.rb
Class Method Summary collapse
Instance Method Summary collapse
- #call(request = ARGV.join(' ').squeeze(' ').strip) ⇒ Object
- #columns(data) ⇒ Object
- #command(args, description, &block) ⇒ Object
- #display_available_commands ⇒ Object
-
#initialize(&block) ⇒ Commando
constructor
A new instance of Commando.
Constructor Details
#initialize(&block) ⇒ Commando
Returns a new instance of Commando.
10 11 12 13 14 15 16 17 18 19 |
# File 'lib/commando.rb', line 10 def initialize(&block) @commands = [] @descriptions = {} @formatador = Formatador.new if block_given? instance_eval(&block) end @finished = true self end |
Class Method Details
.commands(&block) ⇒ Object
6 7 8 |
# File 'lib/commando.rb', line 6 def self.commands(&block) new(&block) end |
Instance Method Details
#call(request = ARGV.join(' ').squeeze(' ').strip) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/commando.rb', line 37 def call(request = ARGV.join(' ').squeeze(' ').strip) for command in @commands if match = command[0].match(request) response = command[1].call(*match.captures) break end end if match @formatador.display_line(response) else display_available_commands end end |
#columns(data) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/commando.rb', line 51 def columns(data) widths = [] for row in data row.length.times do |i| widths[i] = [(widths[i] || 0), row[i].length].max end end lines = [] data.length.times do |row| string = '' data[row].length.times do |column| value = data[row][column] string << "#{value}#{(' ' * (widths[column] - value.length))}" end lines << string lines << '' end lines end |
#command(args, description, &block) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/commando.rb', line 21 def command(args, description, &block) return if @finished args = [*args] command = [] for arg in args case arg when Regexp command << arg.source when String command << Regexp.escape(arg) end end @commands << [/^#{command.join('\s').squeeze('\s')}$/ix, block] @descriptions[command.join(' ').squeeze(' ')] = description end |
#display_available_commands ⇒ Object
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/commando.rb', line 74 def display_available_commands @formatador.display_line("\n[indent][bold]OPTIONS[/]\n") data = [] for command, description in @descriptions data << ["/#{command}/", ' - ', "#{description}"] end @formatador.indent do for column in columns(data) @formatador.display_line(column) end end end |