Class: Dog::Command

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(title) ⇒ Command

Returns a new instance of Command.



5
6
7
8
9
10
# File 'lib/dog/command.rb', line 5

def initialize(title)
  @title = title
  @matchers = []
  @subcommands = []
  @action = ->(input){ }
end

Instance Attribute Details

#titleObject (readonly)

Returns the value of attribute title.



3
4
5
# File 'lib/dog/command.rb', line 3

def title
  @title
end

Instance Method Details

#action(&action) ⇒ Object



12
13
14
# File 'lib/dog/command.rb', line 12

def action(&action)
  @action = action
end

#help(parent_matcher_string = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/dog/command.rb', line 52

def help(parent_matcher_string = nil)
  matchers = @matchers.uniq

  matcher_string = (matchers.count == 1 ? matchers.first.to_s : "{#{matchers.join(',')}}")
  matcher_string = "#{parent_matcher_string} & #{matcher_string}" if parent_matcher_string

  output = "#{@title}: #{matcher_string}\n"
  output += @subcommands.map { |c| c.help(matcher_string) }.inject(:+) unless @subcommands.empty?
  output
end

#matches(*matchers) ⇒ Object



16
17
18
# File 'lib/dog/command.rb', line 16

def matches(*matchers)
  @matchers += matchers
end

#matches?(input_string) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
25
26
27
28
# File 'lib/dog/command.rb', line 20

def matches?(input_string)
  @matchers.any? do |matcher|
    if matcher.is_a?(String)
      input_string.match(/(\s|^)#{matcher}(\s|$)/)
    else
      input_string.match(matcher)
    end
  end
end

#respond_to(input_string) ⇒ Object



45
46
47
48
49
50
# File 'lib/dog/command.rb', line 45

def respond_to(input_string)
  if matches?(input_string)
    response = subcommand_response input_string
    response || @action.call(input_string)
  end
end

#subcommand(title, &block) ⇒ Object



30
31
32
33
34
# File 'lib/dog/command.rb', line 30

def subcommand(title, &block)
  subcommand = Command.new title
  subcommand.instance_eval &block
  @subcommands << subcommand
end

#subcommand_response(input_string) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/dog/command.rb', line 36

def subcommand_response(input_string)
  @subcommands.each do |subcommand|
    response = subcommand.respond_to(input_string)
    return response unless response.nil?
  end

  nil
end