Class: Subcommand
- Inherits:
-
Object
- Object
- Subcommand
- Defined in:
- lib/habits/subcommand.rb
Overview
A minimal command line parser for subcommands. CMD SUBCOMMAND ARG1 ARG2 …
Defined Under Namespace
Classes: Cmd
Instance Attribute Summary collapse
-
#subs ⇒ Object
readonly
Returns the value of attribute subs.
Instance Method Summary collapse
-
#default(&blk) ⇒ Object
Set the default command to be called when just the executable is run.
-
#default=(cmd_name) ⇒ Object
Set the default command to be one of the registered subcommands.
-
#help ⇒ Object
Print help of available commands.
-
#initialize ⇒ Subcommand
constructor
A new instance of Subcommand.
-
#parse(args = ARGV) ⇒ Object
Parse command line arguments according to registered commands.
-
#register(cmd_name, args, desc, &blk) ⇒ Object
Register a command with name, arguments, description, and block (blk).
Constructor Details
#initialize ⇒ Subcommand
Returns a new instance of Subcommand.
41 42 43 44 |
# File 'lib/habits/subcommand.rb', line 41 def initialize @default = nil @subs = {} end |
Instance Attribute Details
#subs ⇒ Object (readonly)
Returns the value of attribute subs.
6 7 8 |
# File 'lib/habits/subcommand.rb', line 6 def subs @subs end |
Instance Method Details
#default(&blk) ⇒ Object
Set the default command to be called when just the executable is run.
54 55 56 57 |
# File 'lib/habits/subcommand.rb', line 54 def default(&blk) raise "No block given" unless blk @default = blk end |
#default=(cmd_name) ⇒ Object
Set the default command to be one of the registered subcommands
60 61 62 63 |
# File 'lib/habits/subcommand.rb', line 60 def default=(cmd_name) raise "No subcommand #{cmd_name} registerd" if @subs[cmd_name].nil? @default = @subs[cmd_name].blk end |
#help ⇒ Object
Print help of available commands.
86 87 88 89 90 91 92 93 94 |
# File 'lib/habits/subcommand.rb', line 86 def help puts "\nUsage: #{File.basename($0)} {command} arg1 arg2 ...\n\nCommand Args"+ ' '*32+"Description" @subs.keys.sort.each do |name| printf(" %-12s %-35s %s\n", name, @subs[name].args_str, @subs[name].desc) end puts true end |
#parse(args = ARGV) ⇒ Object
Parse command line arguments according to registered commands.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/habits/subcommand.rb', line 66 def parse(args=ARGV) if args.size == 0 @default.call if @default return end sub = @subs[args.shift] help and return if sub.nil? begin sub.parse(args) sub.call rescue Exception => e puts e. help end end |
#register(cmd_name, args, desc, &blk) ⇒ Object
Register a command with name, arguments, description, and block (blk). The block is called with as many input args as you defined in ‘args’
48 49 50 51 |
# File 'lib/habits/subcommand.rb', line 48 def register(cmd_name, args, desc, &blk) @subs ||= {} @subs[cmd_name] = Cmd.new(args, desc, blk) end |