Class Erubis::TinyEruby
In: 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

Methods

convert   escape_text   evaluate   new   result  

Constants

EMBEDDED_PATTERN = /<%(=+|\#)?(.*?)-?%>/m

Attributes

src  [R] 

Public Class methods

[Source]

# File erubis/tiny.rb, line 20
    def initialize(input=nil)
      @src = convert(input) if input
    end

Public Instance methods

[Source]

# File erubis/tiny.rb, line 27
    def convert(input)
      src = "_buf = [];"           # preamble
      pos = 0
      input.scan(EMBEDDED_PATTERN) do |indicator, code|
        match = Regexp.last_match
        index = match.begin(0)
        text  = input[pos, index - pos]
        pos   = match.end(0)
        src << " _buf << '" << escape_text(text) << "';"
        if !indicator              # <% %>
          src << code << ";"
        elsif indicator[0] == ?\#  # <%# %>
          n = code.count("\n")
          add_stmt(src, "\n" * n)
        else                       # <%= %>
          src << " _buf << (" << code << ").to_s;"
        end
      end
      rest = $' || input
      src << " _buf << '" << escape_text(rest) << "';"
      src << "\n_buf.join\n"       # postamble
      return src
    end

[Source]

# File erubis/tiny.rb, line 51
    def escape_text(text)
      return text.gsub!(/['\\]/, '\\\\\&') || text
    end

[Source]

# File erubis/tiny.rb, line 59
    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

[Source]

# File erubis/tiny.rb, line 55
    def result(binding=TOPLEVEL_BINDING)
      eval @src, binding
    end

[Validate]