Class: URITemplate::RegexpEnumerator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/uri_template/utils.rb

Overview

An awesome little helper which helps iterating over a string. Initialize with a regexp and pass a string to :each. It will yield a string or a MatchData

Instance Method Summary (collapse)

Constructor Details

- (RegexpEnumerator) initialize(regexp, options = {})

A new instance of RegexpEnumerator



27
28
29
30
# File 'lib/uri_template/utils.rb', line 27

def initialize(regexp, options = {})
  @regexp = regexp
  @rest = options.fetch(:rest){ :yield }
end

Instance Method Details

- (Object) each(str)

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/uri_template/utils.rb', line 32

def each(str)
  raise ArgumentError, "RegexpEnumerator#each expects a String, but got #{str.inspect}" unless str.kind_of? String
  return Enumerator.new(self,:each,str) unless block_given?
  rest = str
  loop do
    m = @regexp.match(rest)
    if m.nil?
      if rest.size > 0
        yield rest if @rest == :yield
        raise "Unable to match #{rest.inspect} against #{@regexp.inspect}" if @rest == :raise
      end
      break
    end
    yield m.pre_match if m.pre_match.size > 0
    yield m
    if m[0].size == 0
      # obviously matches empty string, so post_match will equal rest
      # terminate or this will loop forever
      if m.post_match.size > 0
        yield m.post_match if @rest == :yield
        raise "#{@regexp.inspect} matched an empty string. The rest is #{m.post_match.inspect}." if @rest == :raise
      end
      break
    end
    rest = m.post_match
  end
  return self
end