Class: Attentive::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/attentive/matcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(phrase, message, params = {}) ⇒ Matcher

Returns a new instance of Matcher.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/attentive/matcher.rb', line 7

def initialize(phrase, message, params={})
  @phrase = phrase
  @match_start = message.pos
  @cursor = Cursor.new(phrase, params.fetch(:pos, 0))
  @message = message
  self.message.pop while self.message.peek.whitespace?
  @match_params = params.merge(message: message.message, match_start: message.pos)
  @match_data = {}
  @state = :matching

  cursor.pop while cursor.peek.whitespace?
end

Instance Attribute Details

#cursorObject (readonly)

Returns the value of attribute cursor.



5
6
7
# File 'lib/attentive/matcher.rb', line 5

def cursor
  @cursor
end

#messageObject (readonly)

Returns the value of attribute message.



5
6
7
# File 'lib/attentive/matcher.rb', line 5

def message
  @message
end

#phraseObject (readonly)

Returns the value of attribute phrase.



5
6
7
# File 'lib/attentive/matcher.rb', line 5

def phrase
  @phrase
end

Instance Method Details

#match!Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/attentive/matcher.rb', line 32

def match!
  until (token = message.peek).eof?
    if token.ambiguous?
      unless match_any!(token.possibilities)
        @state = :mismatch
        break
      end
      message.pop
      cursor.pop while cursor.peek.whitespace?

    elsif match_data = cursor.peek.matches?(message)
      @match_data.merge!(match_data) unless match_data == true
      cursor.pop
      cursor.pop while cursor.peek.whitespace?
      @state = :found

      # -> This is the one spot where we instantiate a Match
      return Attentive::Match.new(phrase, @match_params.merge(
        match_end: message.pos,
        match_data: @match_data)) if cursor.eof?

    elsif token.skippable?
      message.pop

    else
      @state = :mismatch
      break
    end

    message.pop while message.peek.whitespace?
  end

  nil
end

#match_any!(messages) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/attentive/matcher.rb', line 67

def match_any!(messages)
  messages.each do |message|
    matcher = Matcher.new(phrase[pos..-1], Cursor.new(message))
    matcher.match!
    unless matcher.mismatch?
      cursor.advance matcher.pos
      return true
    end
  end

  false
end

#matching?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/attentive/matcher.rb', line 24

def matching?
  @state == :matching
end

#mismatch?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/attentive/matcher.rb', line 28

def mismatch?
  @state == :mismatch
end

#posObject



20
21
22
# File 'lib/attentive/matcher.rb', line 20

def pos
  cursor.pos
end