Class: D13n::Cli::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/d13n/cli/command.rb

Direct Known Subclasses

Scaffold

Defined Under Namespace

Classes: CommandFailure

Class Method Summary collapse

Instance Method Summary collapse

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 = 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.message, @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

.runObject



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 = []

  options = ARGV.options do |opts|
    script_name = File.basename($0)
    opts.banner = "Usage: #{script_name} [ #{ @command_names.join(" | ")} ] [options]"
    opts.separator "use '#{script_name} <command> -h' to see detailed command options"
    opts
  end
  extra = options.order!
  command = extra.shift

  if command.nil?
    STDOUT.puts "No command provided"
    STDOUT.puts options.to_s
  elsif !@command_names.include?(command)
    STDOUT.puts "Unrecognized command: #{command}"
    STDOUT.puts options
  else
    command_class = @commands.find{ |c| c.command == command}
    command_class.new(extra).run
  end
rescue OptionParser::InvalidOption => e
  raise CommandFailure.new(e.message)
end

Instance Method Details

#runObject

Raises:

  • (NotImplementedError)


70
71
72
# File 'lib/d13n/cli/command.rb', line 70

def run
  raise NotImplementedError, 'Command class must be able to #run!'
end