Class: Packr::RegexpGroup::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/packr/base2/regexp_group.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression, replacement = nil) ⇒ Item

Returns a new instance of Item.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/packr/base2/regexp_group.rb', line 73

def initialize(expression, replacement = nil)
  @expression = expression
  
  if replacement.nil?
    replacement = IGNORE
  elsif replacement.respond_to?(:replacement)
    replacement = replacement.replacement
  elsif !replacement.is_a?(Proc)
    replacement = replacement.to_s
  end
  
  # does the pattern use sub-expressions?
  if replacement.is_a?(String) and replacement =~ LOOKUP
    # a simple lookup? (e.g. "\2")
    if replacement.gsub(/\n/, " ") =~ LOOKUP_SIMPLE
      # store the index (used for fast retrieval of matched strings)
      replacement = replacement[1..-1].to_i
    else # a complicated lookup (e.g. "Hello \2 \1")
      # build a function to do the lookup
      # Improved version by Alexei Gorkov:
      q = '"'
      replacement_string = replacement.
          gsub(/\\/, "\\\\").
          gsub(/"/, "\\x22").
          gsub(/\n/, "\\n").
          gsub(/\r/, "\\r").
          gsub(/\\(\d+)/, q + "+(args[\\1]||" + q+q + ")+" + q).
          gsub(/(['"])\1\+(.*)\+\1\1$/, '\1')
      replacement = lambda { |*args| eval(q + replacement_string + q) }
      
      # My old crappy version:
      # q = (replacement.gsub(/\\./, "") =~ /'/) ? '"' : "'"
      # replacement = replacement.gsub(/\r/, "\\r").gsub(/\\(\d+)/,
      #     q + "+(args[\\1]||" + q+q + ")+" + q)
      # replacement_string = q + replacement.gsub(/(['"])\1\+(.*)\+\1\1$/, '\1') + q
      # replacement = lambda { |*args| eval(replacement_string) }
    end
  end
  
  @length = RegexpGroup.count(@expression)
  @replacement = replacement
end

Instance Attribute Details

#expressionObject

Returns the value of attribute expression.



71
72
73
# File 'lib/packr/base2/regexp_group.rb', line 71

def expression
  @expression
end

#lengthObject

Returns the value of attribute length.



71
72
73
# File 'lib/packr/base2/regexp_group.rb', line 71

def length
  @length
end

#replacementObject

Returns the value of attribute replacement.



71
72
73
# File 'lib/packr/base2/regexp_group.rb', line 71

def replacement
  @replacement
end

Instance Method Details

#to_sObject



116
117
118
# File 'lib/packr/base2/regexp_group.rb', line 116

def to_s
  @expression.respond_to?(:source) ? @expression.source : @expression.to_s
end