Class: MCLI::Command

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

Direct Known Subclasses

NullCommand

Defined Under Namespace

Classes: Option

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = []) ⇒ Command

Returns a new instance of Command.



4
5
6
# File 'lib/mcli/command.rb', line 4

def initialize(args=[])
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



2
3
4
# File 'lib/mcli/command.rb', line 2

def args
  @args
end

Class Method Details

.callObject



76
77
78
79
80
81
82
83
84
85
# File 'lib/mcli/command.rb', line 76

def call
  new(ARGV).tap do |command|
    begin
      command.parse unless capture_all?
      command.run
    rescue MCLI::HelpError
      command.help
    end
  end
end

.capture_all!Object



68
69
70
# File 'lib/mcli/command.rb', line 68

def capture_all!
  @capture_all = true
end

.capture_all?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/mcli/command.rb', line 72

def capture_all?
  @capture_all
end

.description(desc = nil) ⇒ Object



47
48
49
50
# File 'lib/mcli/command.rb', line 47

def description(desc=nil)
  @description = desc unless desc.nil?
  @description ||= ''
end

.option(option_name, opts = {}) ⇒ Object



52
53
54
# File 'lib/mcli/command.rb', line 52

def option(option_name, opts={})
  options << Option.new(option_name, opts)
end

.optionsObject



56
57
58
# File 'lib/mcli/command.rb', line 56

def options
  @options ||= []
end

.register_as(command_name) ⇒ Object



60
61
62
# File 'lib/mcli/command.rb', line 60

def register_as(command_name)
  MCLI::CommandGroup.register(command_name, self)
end

.register_as_rootObject



64
65
66
# File 'lib/mcli/command.rb', line 64

def register_as_root
  MCLI::CommandGroup.register_root(self)
end

Instance Method Details

#create_parserObject



38
39
40
41
42
43
44
# File 'lib/mcli/command.rb', line 38

def create_parser
  OptionParser.new.tap do |parser|
    parser.on("-h", "--help", "Help") do
      raise MCLI::HelpError.new
    end
  end
end

#optionsObject



30
31
32
# File 'lib/mcli/command.rb', line 30

def options
  @options ||= {}
end

#parseObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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!

  self.class.options
    .select { |option| option.required == true }
    .map do |required_option|
      if @options[required_option.name].nil?
        raise OptionParser::MissingArgument
      end
    end
end

#parserObject



34
35
36
# File 'lib/mcli/command.rb', line 34

def parser
  @parser ||= create_parser
end