Class: D13n::Cli::Command
- Inherits:
-
Object
- Object
- D13n::Cli::Command
- Defined in:
- lib/d13n/cli/command.rb
Direct Known Subclasses
Defined Under Namespace
Classes: CommandFailure
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(args) ⇒ Command
constructor
A new instance of Command.
- #run ⇒ Object
Constructor Details
#initialize(args) ⇒ Command
Returns a new instance of Command.
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/d13n/cli/command.rb', line 17 def initialize(args) if Hash === args args.each do |k, v| instance_variable_set "@#{k}", v.to_s if v end else @options = do |opts| opts.on("-h", "Show this help") { raise CommandFailure, opts.to_s } end raise CommandFailure, @options.to_s if args.empty? @leftover = @options.parse(args) end rescue OptionParser::ParseError => e raise CommandFailure.new(e., @options) end |
Class Method Details
.inherited(subclass) ⇒ Object
35 36 37 |
# File 'lib/d13n/cli/command.rb', line 35 def self.inherited(subclass) @commands << subclass end |
.run ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/d13n/cli/command.rb', line 42 def self.run @command_names = @commands.map{ |c| c.command} extra = [] = ARGV. do |opts| script_name = File.basename($0) opts. = "Usage: #{script_name} [ #{ @command_names.join(" | ")} ] [options]" opts.separator "use '#{script_name} <command> -h' to see detailed command options" opts end extra = .order! command = extra.shift if command.nil? STDOUT.puts "No command provided" STDOUT.puts .to_s elsif !@command_names.include?(command) STDOUT.puts "Unrecognized command: #{command}" STDOUT.puts else command_class = @commands.find{ |c| c.command == command} command_class.new(extra).run end rescue OptionParser::InvalidOption => e raise CommandFailure.new(e.) end |
Instance Method Details
#run ⇒ Object
70 71 72 |
# File 'lib/d13n/cli/command.rb', line 70 def run raise NotImplementedError, 'Command class must be able to #run!' end |