module Util
require 'util'
Public Class Methods
mgsub(string, substitution_hash)
click to toggle source
Multiple Global Substitution.
substitution_hash contains pattern (regexp or string) keys and corresponding substitution. Substitution can either be a string or a function of regexp MatchData. The latter allows for arbitrary substitution based on matched content.
# File lib/util.rb, line 18 def self.mgsub(string, substitution_hash) regexp_hash = {} substitution_hash.each do |key, substitution| regexp = to_regexp(key) regexp_hash[regexp] = substitution end combined_regexp = Regexp.union(*regexp_hash.keys) substitution_function = make_substitution_function(regexp_hash) string.gsub(combined_regexp, &substitution_function) end
Private Class Methods
make_substitution_function(regexp_hash)
click to toggle source
We can't use a closure (for now) because JRuby (as of 1.7.14) doesn't handle return correctly in lambdas. It returns from the containing function. Here we depend on an early return from the actual function only.
# File lib/util.rb, line 49 def self.make_substitution_function(regexp_hash) ->(matched_string) { result = nil # Poor man's early return because of JRuby bug. regexp_hash.each do |regexp, substitution| if !result && matched_string.match(regexp) match_data = Regexp.last_match result = case substitution when String substitution else substitution.call(match_data) end end end result } end
to_regexp(spec)
click to toggle source
Return corresponding regexp, escaping string if necessary. Regexp returns itself.
# File lib/util.rb, line 38 def self.to_regexp(spec) case spec when Regexp spec when String Regexp.escape(spec) end end
Public Instance Methods
mgsub(string, substitution_hash)
click to toggle source
Sugar to allow calling mgsub as instance method.
# File lib/util.rb, line 7 def mgsub(string, substitution_hash) Util::mgsub(string, substitution_hash) end