Class: Rack::Mount::RegexpWithNamedGroups

Inherits:
Regexp
  • Object
show all
Defined in:
lib/rack/mount/regexp_with_named_groups.rb

Overview

A wrapper that adds shim named capture support to older versions of Ruby.

Because the named capture syntax causes a parse error, an alternate syntax is used to indicate named captures.

Ruby 1.9+ named capture syntax:

/(?<foo>[a-z]+)/

Ruby 1.8 shim syntax:

/(?:<foo>[a-z]+)/

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(regexp) ⇒ RegexpWithNamedGroups

Wraps Regexp with named capture support.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rack/mount/regexp_with_named_groups.rb', line 30

def initialize(regexp)
  regexp = Regexp.compile(regexp) unless regexp.is_a?(Regexp)
  source, options = regexp.source, regexp.options
  @names, scanner = [], StringScanner.new(source)

  while scanner.skip_until(/\(/)
    if scanner.scan(/\?:<([^>]+)>/)
      @names << scanner[1]
    elsif scanner.scan(/\?(i?m?x?\-?i?m?x?)?:/)
      # ignore noncapture
    else
      @names << nil
    end
  end
  source.gsub!(/\?:<([^>]+)>/, '')

  @names = [] unless @names.any?
  @names.freeze

  super(source, options)
end

Class Method Details

.new(regexp) ⇒ Object

:nodoc:



21
22
23
24
25
26
27
# File 'lib/rack/mount/regexp_with_named_groups.rb', line 21

def self.new(regexp) #:nodoc:
  if regexp.is_a?(RegexpWithNamedGroups)
    regexp
  else
    super
  end
end

Instance Method Details

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/rack/mount/regexp_with_named_groups.rb', line 64

def eql?(other)
  super && @names.eql?(other.names)
end

#named_capturesObject



56
57
58
59
60
61
62
# File 'lib/rack/mount/regexp_with_named_groups.rb', line 56

def named_captures
  named_captures = {}
  names.each_with_index { |n, i|
    named_captures[n] = [i+1] if n
  }
  named_captures
end

#namesObject



52
53
54
# File 'lib/rack/mount/regexp_with_named_groups.rb', line 52

def names
  @names.dup
end