Module: Irregular

Defined in:
lib/irregular.rb,
lib/irregular/version.rb

Constant Summary collapse

VERSION =

Attempt to keep in sync with the earliest irregular-js version that exhibits the same compilation behavior

"1.0.1"

Instance Method Summary collapse

Instance Method Details

#compile_regexp(regexp_or_string, options = 0) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/irregular.rb', line 4

def compile_regexp(regexp_or_string, options = 0)
  if regexp_or_string.is_a? Regexp
    source = regexp_or_string.source
    options |= regexp_or_string.options
  end

  if regexp_or_string.is_a? String
    source = regexp_or_string
  end

  # Ruby regular expressions don't support the global flag,
  # so we scan to collect results then gsub them in
  # instead of passing a block directly to match.

  template_regexp = /`(\w+)`/

  compiled_results = {}
  source.scan(template_regexp) do
    compiled_results[$1] = if respond_to?($1)
      send($1)
    else
      "`#{$1}`"
    end
  end

  compiled_source = source.gsub(template_regexp) do
    compiled_results[$1]
  end

  Regexp.new(compiled_source, options)
end