| Class | Erubis::TinyEruby |
| In: |
lib/erubis/tiny.rb
|
| Parent: | Object |
tiny and the simplest implementation of eRuby
ex.
eruby = TinyEruby.new(File.read('example.rhtml'))
print eruby.src # print ruby code
print eruby.result(binding()) # eval ruby code with Binding object
print eruby.evalute(context) # eval ruby code with context object
| EMBEDDED_PATTERN | = | /<%(=+|\#)?(.*?)-?%>/m |
| src | [R] |
# File lib/erubis/tiny.rb, line 20
20: def initialize(input=nil)
21: @src = convert(input) if input
22: end
# File lib/erubis/tiny.rb, line 27
27: def convert(input)
28: src = "_buf = '';" # preamble
29: pos = 0
30: input.scan(EMBEDDED_PATTERN) do |indicator, code|
31: match = Regexp.last_match
32: len = match.begin(0) - pos
33: text = input[pos, len]
34: pos = match.end(0)
35: #src << " _buf << '" << escape_text(text) << "';"
36: text.gsub!(/['\\]/, '\\\\\&')
37: src << " _buf << '" << text << "';" unless text.empty?
38: if !indicator # <% %>
39: src << code << ";"
40: elsif indicator == '#' # <%# %>
41: src << ("\n" * code.count("\n"))
42: else # <%= %>
43: src << " _buf << (" << code << ").to_s;"
44: end
45: end
46: #rest = $' || input # ruby1.8
47: rest = pos == 0 ? input : input[pos..-1] # ruby1.9
48: #src << " _buf << '" << escape_text(rest) << "';"
49: rest.gsub!(/['\\]/, '\\\\\&')
50: src << " _buf << '" << rest << "';" unless rest.empty?
51: src << "\n_buf.to_s\n" # postamble
52: return src
53: end
# File lib/erubis/tiny.rb, line 63
63: def evaluate(_context=Object.new)
64: if _context.is_a?(Hash)
65: _obj = Object.new
66: _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end
67: _context = _obj
68: end
69: _context.instance_eval @src
70: end