Class: Prompt::Command

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

Constant Summary collapse

SEP =

RS - record separator

"\036"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(words, desc = nil, &block) ⇒ Command

Returns a new instance of Command.



14
15
16
17
18
19
20
21
22
# File 'lib/prompt/command.rb', line 14

def initialize(words, desc = nil, &block)
  @words = words
  @desc = desc
  @action = block

  @name = words.join(" ")
  @matchers = words.select {|w| w.kind_of?(Matcher) }
  @parameters = @matchers.map { |m| m.parameter }
end

Instance Attribute Details

#descObject (readonly)

Returns the value of attribute desc.



11
12
13
# File 'lib/prompt/command.rb', line 11

def desc
  @desc
end

#nameObject (readonly)

Returns the value of attribute name.



10
11
12
# File 'lib/prompt/command.rb', line 10

def name
  @name
end

#parametersObject (readonly)

Returns the value of attribute parameters.



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

def parameters
  @parameters
end

Instance Method Details

#clear_cached_valuesObject



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

def clear_cached_values
  @parameters.each do |p|
    p.clear_cached_values if p.respond_to?(:clear_cached_values)
  end
end

#completions(word_idx, starting_with) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/prompt/command.rb', line 53

def completions(word_idx, starting_with)
  idx = @words[0...word_idx].find_index { |w| w.kind_of? MultiMatcher } || word_idx
  word = @words[idx]
  return [] if word.nil?

  next_word = @words[idx+1]

  if idx < word_idx and next_word
    completions_for(word, starting_with) + completions_for(next_word, starting_with)
  else
    completions_for(word, starting_with)
  end
end

#could_match?(words) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/prompt/command.rb', line 67

def could_match?(words)
  words.each_with_index do |w, i|
    word = @words[i]
    case word
    when nil
      return false
    when MultiMatcher
      return true
    when String
      return false unless word.start_with?(w)
    end
  end
  return true
end

#match(words) ⇒ Object



28
29
30
31
32
# File 'lib/prompt/command.rb', line 28

def match words
  if args = regex.match(words.join(SEP))
    @matchers.map {|m| m.matches(args[m.parameter.name]) }
  end
end

#run(args) ⇒ Object



24
25
26
# File 'lib/prompt/command.rb', line 24

def run args
  @action.call *args
end

#usageObject



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/prompt/command.rb', line 34

def usage
  @words.map do |word|
    case word
    when MultiMatcher
      "<#{word.parameter.name}> ..."
    when Matcher
      "<#{word.parameter.name}>"
    else
      word
    end
  end.join(" ")
end