class MisterBin::Runner
Attributes
commands[R]
handler[R]
header[R]
version[R]
Public Class Methods
new(opts={})
click to toggle source
# File lib/mister_bin/runner.rb, line 9 def initialize(opts={}) @header = opts[:header] @footer = opts[:footer] @version = opts[:version] @commands = opts[:commands] || {} @handler = opts[:handler] end
Public Instance Methods
route(key, to:)
click to toggle source
# File lib/mister_bin/runner.rb, line 17 def route(key, to:) commands[key] = to end
route_all(to:)
click to toggle source
# File lib/mister_bin/runner.rb, line 21 def route_all(to:) @handler = to end
run(argv=[])
click to toggle source
# File lib/mister_bin/runner.rb, line 25 def run(argv=[]) if handler handler.execute argv elsif argv.empty? show_subs elsif argv == ['--help'] or argv == ['-h'] show_help elsif version and (argv == ['--version'] or argv == ['-v']) puts version return 1 else execute argv end end
Private Instance Methods
execute(argv)
click to toggle source
# File lib/mister_bin/runner.rb, line 42 def execute(argv) argv = normalize_argv_command argv command = commands[argv[0]] if command command.execute argv else say "!txtred!Unknown command\n" show_subs end end
normalize_argv_command(argv)
click to toggle source
# File lib/mister_bin/runner.rb, line 54 def normalize_argv_command(argv) command = argv[0] return argv if commands.has_key? command candidates = commands.keys.select { |key| key =~ /^#{command}/ } argv[0] = candidates.first if candidates.count == 1 argv end
show_help()
click to toggle source
# File lib/mister_bin/runner.rb, line 88 def show_help if commands.empty? say "No subcommands found" else show_help! end return 1 end
show_help!()
click to toggle source
# File lib/mister_bin/runner.rb, line 98 def show_help! say "#{header}\n" if header commands.each do |key, command| meta = command.meta next unless meta.help or meta.summary say "!txtgrn!#{key}" help = meta.help || meta.summary say word_wrap " #{help}" say "" end say "#{footer}" if footer end
show_subs()
click to toggle source
# File lib/mister_bin/runner.rb, line 62 def show_subs if commands.empty? say "No subcommands found" else show_subs! end return 1 end
show_subs!()
click to toggle source
# File lib/mister_bin/runner.rb, line 72 def show_subs! longest_key = commands.keys.max_by(&:size).size max_summary_size = terminal_width - longest_key - 6 say "#{header}\n" if header say "Commands:" commands.each do |key, command| summary = command.meta.description summary = summary[0..max_summary_size].strip say " !bldgrn!#{key.ljust longest_key} !txtrst!#{summary}" end say "\n#{footer}" if footer end