module CLI::Commands
Commands is like a factory.
lists commands in lib/commands directory, allowing subcommands
(as seen in git, for example).
Each command should have its own help, responding on --help.
Sample of use:
CLI::Commands.from_app(self).parse
Attributes
app_name[R]
Public Class Methods
dir()
click to toggle source
# File lib/cli.rb, line 24 def self.dir Pathname.new(__FILE__).realpath.dirname.join('commands') end
from_app(app)
click to toggle source
# File lib/cli/commands.rb, line 38 def self.from_app(app) self.app_name = app.app_name return self end
list()
click to toggle source
# File lib/cli/commands.rb, line 22 def self.list commands = { } self.dir.entries.each do |entry| next if entry.to_s[0] == '.' entry = self.dir.join(entry).realpath fname = entry.basename.to_s m = /^((.*)_command)\.rb$/.match(fname) if m and m[2] struct = OpenStruct.new(:path => entry, :class_name => 'Commands::%s' % m[1].camel_case) commands[m[2].underscore.to_sym] = struct end end return commands end
parse()
click to toggle source
# File lib/cli/commands.rb, line 43 def self.parse commands = self.load command = (ARGV[0] and ARGV[0][0] != "-") ? ARGV[0].to_sym : nil parser = OptionParser.new do |opts| opts.banner = "Usage: %s %s" % [self.app_name, commands.cli_options] opts.on('-h', '--help', 'Display this screen') do $stdout.puts opts exit 0 end end parser.parse! if not command if not commands.include? command raise ArgumentError.new('Unknown command "%s"' % command) else ARGV.delete_at(0) Kernel.constantize(commands[command].class_name).execute end end
Protected Class Methods
app_name=(app_name)
click to toggle source
# File lib/cli/commands.rb, line 63 def self.app_name=(app_name) @app_name = app_name end
load()
click to toggle source
# File lib/cli/commands.rb, line 67 def self.load items = self.list items.each {|k,v| require(v.path) } return items end