Class: Walrat::MatchDataWrapper

Inherits:
Object
  • Object
show all
Includes:
LocationTracking
Defined in:
lib/walrat/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

Attributes included from LocationTracking

#outer_end, #outer_source_text, #outer_start, #source_text

Instance Method Summary collapse

Methods included from LocationTracking

#column_end, #column_end=, #column_start, #column_start=, #end, #end=, #line_end, #line_end=, #line_start, #line_start=, #rightmost?, #start, #start=

Constructor Details

#initialize(data) ⇒ MatchDataWrapper

Raises if data is nil.

Raises:

  • (ArgumentError)


41
42
43
44
# File 'lib/walrat/match_data_wrapper.rb', line 41

def initialize data
  raise ArgumentError, 'nil data' if data.nil?
  self.match_data = data
end

Instance Attribute Details

#match_dataObject

Returns the value of attribute match_data.



38
39
40
# File 'lib/walrat/match_data_wrapper.rb', line 38

def match_data
  @match_data
end

Instance Method Details

#==(other) ⇒ Object

Although this method explicitly allows for MatchDataWrapper to MatchDataWrapper comparisons, note 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.



60
61
62
63
64
65
66
67
68
# File 'lib/walrat/match_data_wrapper.rb', line 60

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



74
75
76
# File 'lib/walrat/match_data_wrapper.rb', line 74

def jlength
  self.to_s.jlength
end

#to_sObject



70
71
72
# File 'lib/walrat/match_data_wrapper.rb', line 70

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.



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

def to_str
  self.to_s
end