Class: Subcommand::Cmd

Inherits:
Object
  • Object
show all
Defined in:
lib/habits/subcommand.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args, desc, blk) ⇒ Cmd

Returns a new instance of Cmd.



11
12
13
14
# File 'lib/habits/subcommand.rb', line 11

def initialize(args, desc, blk)
  @args, @desc, @blk = args, desc, blk
  @optional = @args.pop if @args.last =~ /^\[.*\]$/
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



9
10
11
# File 'lib/habits/subcommand.rb', line 9

def args
  @args
end

#blkObject (readonly)

Returns the value of attribute blk.



9
10
11
# File 'lib/habits/subcommand.rb', line 9

def blk
  @blk
end

#descObject (readonly)

Returns the value of attribute desc.



9
10
11
# File 'lib/habits/subcommand.rb', line 9

def desc
  @desc
end

Instance Method Details

#args_strObject



16
17
18
# File 'lib/habits/subcommand.rb', line 16

def args_str
  (@args + [@optional]).compact.join(' ')
end

#callObject

Trigger this command



30
31
32
33
34
35
36
37
38
# File 'lib/habits/subcommand.rb', line 30

def call
  if @optional # provide nil for the optional arg in block if needed
    args = @call_args
    args << nil if @call_args.size == @args.size
    blk.call *args
  else
    blk.call *@call_args
  end
end

#parse(args) ⇒ Object

Parse @call_args for this command



21
22
23
24
25
26
27
# File 'lib/habits/subcommand.rb', line 21

def parse(args)
  if (args.size == @args.size) or (@optional and args.size == @args.size+1)
    @call_args = args
  else
    raise "Invalid arguments."
  end
end