class Decline::Command

Attributes

config[R]
parser[R]
subcommands[R]

Public Class Methods

new() click to toggle source
# File lib/decline/command.rb, line 8
def initialize
  @config = OpenStruct.new
  @parser = OptionParser.new
  @subcommands ||= Hash.new
  self.options(@parser) # Callback to the child class
end

Public Instance Methods

add_command(name, command) click to toggle source
# File lib/decline/command.rb, line 15
def add_command(name, command)
  command.add_options do |cli|
    cli.set_program_name "#{parser.program_name} #{name}"
  end

  subcommands[name.to_s] = command

  self
end
add_options(&block) click to toggle source
# File lib/decline/command.rb, line 25
def add_options(&block)
  block.call(parser)
  self
end
run(argv, parent_config={}) click to toggle source
# File lib/decline/command.rb, line 30
def run(argv, parent_config={})
  merge_config(parent_config)
  # I didn't want to use `order!` here because it will mutate argv, but it
  parsed_args = Array(parser.order!(argv))
  call_command(parsed_args)
end

Protected Instance Methods

call(*args) click to toggle source

Default call method. This should be overridden.

# File lib/decline/command.rb, line 44
def call(*args)
  puts parser.help
  exit 1
end
options(cli) click to toggle source
# File lib/decline/command.rb, line 39
def options(cli)
  #noop
end

Private Instance Methods

call_command(argv) click to toggle source
# File lib/decline/command.rb, line 65
def call_command(argv)
  if has_subcommand? argv.first
    call_subcommand(*argv)
  else
    call(argv) # Callback to child class
  end
end
call_subcommand(name, *argv) click to toggle source
# File lib/decline/command.rb, line 60
def call_subcommand(name, *argv)
  cmd = subcommands[name]
  cmd.run(argv, config)
end
has_subcommand?(name) click to toggle source
# File lib/decline/command.rb, line 56
def has_subcommand?(name)
  subcommands.has_key?(name)
end
merge_config(other) click to toggle source
# File lib/decline/command.rb, line 51
def merge_config(other)
  # Ugly way to merge openstructs and/or hashes
  @config = OpenStruct.new other.to_h.merge(config.to_h)
end