Class: Attentive::Tokens::Regexp

Inherits:
Attentive::Token show all
Defined in:
lib/attentive/tokens/regexp.rb

Instance Attribute Summary collapse

Attributes inherited from Attentive::Token

#begin

Instance Method Summary collapse

Methods inherited from Attentive::Token

#ambiguous?, #end, #entity?, #eof?, #inspect, #skippable?, #whitespace?

Constructor Details

#initialize(string, pos) ⇒ Regexp

Returns a new instance of Regexp.



8
9
10
11
# File 'lib/attentive/tokens/regexp.rb', line 8

def initialize(string, pos)
  @regexp = ::Regexp.compile("^#{string}")
  super pos
end

Instance Attribute Details

#regexpObject (readonly)

Returns the value of attribute regexp.



6
7
8
# File 'lib/attentive/tokens/regexp.rb', line 6

def regexp
  @regexp
end

Instance Method Details

#==(other) ⇒ Object



13
14
15
# File 'lib/attentive/tokens/regexp.rb', line 13

def ==(other)
  self.class == other.class && self.regexp == other.regexp
end

#matches?(cursor) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/attentive/tokens/regexp.rb', line 17

def matches?(cursor)
  # Compare the original, untokenized, message to the regular expression
  match_data = regexp.match(cursor.to_s)
  return false unless match_data

  # Find the first token following the match
  new_character_index = cursor.offset + match_data.to_s.length
  cursor_pos = cursor.tokens.index { |token| token.begin >= new_character_index }
  cursor_pos = cursor.tokens.length unless cursor_pos

  # If the match ends in the middle of a token, treat it as a mismatch
  match_end_token = cursor.tokens[cursor_pos - 1]
  return false if match_end_token.begin + match_end_token.length > new_character_index

  # Advance the cursor to the first token after the regexp match
  cursor.advance cursor_pos - cursor.pos

  # Return the MatchData as a hash
  Hash[match_data.names.zip(match_data.captures)]
end

#to_sObject



38
39
40
# File 'lib/attentive/tokens/regexp.rb', line 38

def to_s
  regexp.inspect
end