Class: Erubis::TinyEruby
- Inherits:
-
Object
- Object
- Erubis::TinyEruby
- Defined in:
- lib/erubis/tiny.rb
Overview
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
Constant Summary collapse
- EMBEDDED_PATTERN =
/<%(=+|\#)?(.*?)-?%>/m
Instance Attribute Summary collapse
-
#src ⇒ Object
readonly
Returns the value of attribute src.
Instance Method Summary collapse
- #convert(input) ⇒ Object
- #evaluate(_context = Object.new) ⇒ Object
-
#initialize(input = nil) ⇒ TinyEruby
constructor
A new instance of TinyEruby.
-
#result(_binding = TOPLEVEL_BINDING) ⇒ Object
def escape_text(text) return text.gsub!(//, ‘\\&’) || text end.
Constructor Details
#initialize(input = nil) ⇒ TinyEruby
Returns a new instance of TinyEruby.
19 20 21 |
# File 'lib/erubis/tiny.rb', line 19 def initialize(input=nil) @src = convert(input) if input end |
Instance Attribute Details
#src ⇒ Object (readonly)
Returns the value of attribute src.
22 23 24 |
# File 'lib/erubis/tiny.rb', line 22 def src @src end |
Instance Method Details
#convert(input) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/erubis/tiny.rb', line 26 def convert(input) src = "_buf = '';" # preamble pos = 0 input.scan(EMBEDDED_PATTERN) do |indicator, code| m = Regexp.last_match text = input[pos...m.begin(0)] pos = m.end(0) #src << " _buf << '" << escape_text(text) << "';" text.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << text << "';" unless text.empty? if !indicator # <% %> src << code << ";" elsif indicator == '#' # <%# %> src << ("\n" * code.count("\n")) else # <%= %> src << " _buf << (" << code << ").to_s;" end end #rest = $' || input # ruby1.8 rest = pos == 0 ? input : input[pos..-1] # ruby1.9 #src << " _buf << '" << escape_text(rest) << "';" rest.gsub!(/['\\]/, '\\\\\&') src << " _buf << '" << rest << "';" unless rest.empty? src << "\n_buf.to_s\n" # postamble return src end |
#evaluate(_context = Object.new) ⇒ Object
61 62 63 64 65 66 67 68 |
# File 'lib/erubis/tiny.rb', line 61 def evaluate(_context=Object.new) if _context.is_a?(Hash) _obj = Object.new _context.each do |k, v| _obj.instance_variable_set("@#{k}", v) end _context = _obj end _context.instance_eval @src end |
#result(_binding = TOPLEVEL_BINDING) ⇒ Object
def escape_text(text)
return text.gsub!(/['\\]/, '\\\\\&') || text
end
57 58 59 |
# File 'lib/erubis/tiny.rb', line 57 def result(_binding=TOPLEVEL_BINDING) eval @src, _binding end |