class MCLI::Command

Attributes

args[R]

Public Class Methods

call(args) click to toggle source
# File lib/mcli/command.rb, line 87
def call(args)
  new(args).tap do |command|
    begin
      command.parse unless capture_all?
      command.run
    rescue MCLI::HelpError
      command.help
    end
  end
end
capture_all!() click to toggle source
# File lib/mcli/command.rb, line 71
def capture_all!
  @capture_all = true
end
capture_all?() click to toggle source
# File lib/mcli/command.rb, line 75
def capture_all?
  @capture_all
end
command_name() click to toggle source
# File lib/mcli/command.rb, line 79
def command_name
  @command_name
end
default_command_group() click to toggle source
# File lib/mcli/command.rb, line 83
def default_command_group
  MCLI::CommandGroup
end
description(desc=nil) click to toggle source
# File lib/mcli/command.rb, line 49
def description(desc=nil)
  @description = desc unless desc.nil?
  @description ||= ''
end
new(args=[]) click to toggle source
# File lib/mcli/command.rb, line 4
def initialize(args=[])
  @args = args
end
option(option_name, opts={}) click to toggle source
# File lib/mcli/command.rb, line 54
def option(option_name, opts={})
  options << Option.new(option_name, opts)
end
options() click to toggle source
# File lib/mcli/command.rb, line 58
def options
  @options ||= []
end
register_as(command_name, to: default_command_group) click to toggle source
# File lib/mcli/command.rb, line 62
def register_as(command_name, to: default_command_group)
  @command_name = command_name
  to.register(command_name, self)
end
register_as_root(to: default_command_group) click to toggle source
# File lib/mcli/command.rb, line 67
def register_as_root(to: default_command_group)
  to.register_root(self)
end

Public Instance Methods

create_parser() click to toggle source
# File lib/mcli/command.rb, line 38
def create_parser
  OptionParser.new.tap do |parser|
    parser.program_name = self.class.command_name

    parser.on("-h", "--help", "Help") do
      raise MCLI::HelpError.new
    end
  end
end
options() click to toggle source
# File lib/mcli/command.rb, line 30
def options
  @options ||= {}
end
parse() click to toggle source
# File lib/mcli/command.rb, line 8
def parse
  @options = {}

  self.class.options.each do |option|
    @options[option.name] = option.default if option.default

    parser.on(*option.to_args) do |o|
      @options[option.name] = o
    end
  end

  parser.parse!(@args)

  self.class.options
    .select { |option| option.required == true }
    .map do |required_option|
      if @options[required_option.name].nil?
        raise OptionParser::MissingArgument
      end
    end
end
parser() click to toggle source
# File lib/mcli/command.rb, line 34
def parser
  @parser ||= create_parser
end