Method: ERB::Util.tokenize

Defined in:
activesupport/lib/active_support/core_ext/erb/util.rb

.tokenize(source) ⇒ Object

Tokenizes a line of ERB. This is really just for error reporting and nobody should use it.



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'activesupport/lib/active_support/core_ext/erb/util.rb', line 161

def self.tokenize(source) # :nodoc:
  require "strscan"
  source = StringScanner.new(source.chomp)
  tokens = []

  start_re = /<%(?:={1,2}|-|\#|%)?/m
  finish_re = /(?:[-=])?%>/m

  while !source.eos?
    pos = source.pos
    source.scan_until(/(?:#{start_re}|#{finish_re})/)
    raise NotImplementedError if source.matched.nil?
    len = source.pos - source.matched.bytesize - pos

    case source.matched
    when start_re
      tokens << [:TEXT, source.string[pos, len]] if len > 0
      tokens << [:OPEN, source.matched]
      if source.scan(/(.*?)(?=#{finish_re}|\z)/m)
        tokens << [:CODE, source.matched] unless source.matched.empty?
        tokens << [:CLOSE, source.scan(finish_re)] unless source.eos?
      else
        raise NotImplementedError
      end
    when finish_re
      tokens << [:CODE, source.string[pos, len]] if len > 0
      tokens << [:CLOSE, source.matched]
    else
      raise NotImplementedError, source.matched
    end

    unless source.eos? || source.exist?(start_re) || source.exist?(finish_re)
      tokens << [:TEXT, source.rest]
      source.terminate
    end
  end

  tokens
end