Class: Walrus::Grammar::MatchDataWrapper

Inherits:
Object
  • Object
show all
Includes:
LocationTracking
Defined in:
lib/walrus/grammar/match_data_wrapper.rb

Overview

Simple wrapper for MatchData objects that implements length, to_s and to_str methods. By implementing to_str, MatchDataWrappers can be directly compared with Strings using the == method. The original MatchData instance can be obtained using the match_data accessor. Upon creation a clone of the passed in MatchData object is stored; this means that the $~ global variable can be conveniently wrapped without having to worry that subsequent operations will alter the contents of the variable.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ MatchDataWrapper

Raises if data is nil.

Raises:

  • (ArgumentError)


25
26
27
28
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 25

def initialize(data)
  raise ArgumentError if data.nil?
  self.match_data = data
end

Instance Attribute Details

#match_dataObject

Returns the value of attribute match_data.



22
23
24
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 22

def match_data
  @match_data
end

Instance Method Details

#==(other) ⇒ Object

Although this method explicitly allows for MatchDataWrapper to MatchDataWrapper comparisons, not that all such comparisons will return false except for those between instances which were initialized with exactly the same match data instance; this is because the MatchData class itself always returns false when compared with other MatchData instances.



37
38
39
40
41
42
43
44
45
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 37

def ==(other)
  if other.kind_of? MatchDataWrapper
    self.match_data == other.match_data
  elsif other.respond_to? :to_str
    self.to_str == other.to_str
  else
    false
  end
end

#jlengthObject



51
52
53
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 51

def jlength
  self.to_s.jlength
end

#to_sObject



47
48
49
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 47

def to_s
  @match_data[0]
end

#to_strObject

The definition of this method, in conjunction with the == method, allows automatic comparisons with String objects using the == method. This is because in a parser matches essentially are Strings (just like Exceptions and Pathnames); it’s just that this class encapsulates a little more information (the match data) for those who want it.



32
33
34
# File 'lib/walrus/grammar/match_data_wrapper.rb', line 32

def to_str
  self.to_s
end