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

#initialize(regexp, options = {}) ⇒ RegexpEnumerator

Returns a new instance of RegexpEnumerator.



33
34
35
36
# File 'lib/uri_template/utils.rb', line 33

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

Instance Method Details

#each(str) ⇒ Object

Raises:

  • (ArgumentError)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/uri_template/utils.rb', line 38

def each(str)
  raise ArgumentError, "RegexpEnumerator#each expects a String, but got #{str.inspect}" unless str.kind_of? String
  return self.to_enum(:each,str) unless block_given?
  rest = str
  loop do
    m = @regexp.match(rest)
    if m.nil?
      if rest.size > 0
        yield rest
      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