Module: Util

Defined in:
lib/util.rb,
lib/util.rb

Overview

require ‘util’

Defined Under Namespace

Classes: Maybe

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.make_substitution_function(regexp_hash) ⇒ Object

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.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/util.rb', line 10

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

.mgsub(string, substitution_hash) ⇒ Object

mgsub == multiple, global substitution.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/util.rb', line 31

def self.mgsub(string, substitution_hash)
  all_regexps = []
  regexp_hash = {}

  substitution_hash.each do |key, substitution|
    regexp = to_regexp(key)
    all_regexps << regexp 
    regexp_hash[regexp] = substitution
  end

  # puts "all_regexps: #{all_regexps.inspect}"
  combined_regexp = Regexp.union(*all_regexps)
  
  substitution_function = make_substitution_function(regexp_hash)

  string.gsub(combined_regexp, &substitution_function)
end

.to_regexp(spec) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/util.rb', line 49

def self.to_regexp(spec)
  case spec
  when Regexp
    spec
  when String
    Regexp.escape(spec)
  end
end

Instance Method Details

#mgsub(string, substitution_hash) ⇒ Object



4
5
6
# File 'lib/util.rb', line 4

def mgsub(string, substitution_hash)
  Util::mgsub(string, substitution_hash)
end