Class: WillScanString::StringScanner

Inherits:
Object
  • Object
show all
Defined in:
lib/will_scan_string/string_scanner.rb

Instance Method Summary collapse

Instance Method Details

#register_replacement(pattern, replacement) ⇒ Object



3
4
5
6
7
# File 'lib/will_scan_string/string_scanner.rb', line 3

def register_replacement( pattern, replacement )
	@replacements = [] if @replacements.nil?
	@replacements << [ pattern, replacement, @replacements.last.present? ? @replacements.last[2] + (@replacements.last[0].is_a?(Regexp) ? @replacements.last[0].capture_groups.length : 0) + 1 : 0 ]
	@replacements_regexp = nil
end

#replace(string) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/will_scan_string/string_scanner.rb', line 9

def replace( string )
	result = string.dup
	result_offset = 0
	string.scan replacement_regexp do
		match = $~
		r = *execute_replacement_with_match(*get_match_and_replacement(match).reverse)
		replacement = r.last
		is_global = r.first == 1
		return replacement if is_global
		result[(result_offset+match.begin(0))...(result_offset+match.end(0))] = replacement
		result_offset += replacement.length - (match.end(0)-match.begin(0))
	end
	result
end