wycats (owner)

Revisions

gist: 228316 Download_button fork
public
Public Clone URL: git://gist.github.com/228316.git
Embed All Files: show embed
rails_template.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
module CompiledTemplates
end
 
class Template
  def initialize(string)
    @string = string
  end
 
  def render(object)
    # object is assumed to have CompiledTemplates on it
    compile
    object.__send__(@method_name)
  end
 
  def compile
    return if @method_name
    
    name = "_render_#{random_method_name}"
    CompiledTemplates.class_eval <<-RUBY
def #{name}
# actual compiled code
end
RUBY
    @method_name = name
  end
  
  def random_method_name
    ActiveSupport::SecureHash.hex(16)
  end
end
 
Template.new(template_string).render(ActionView::Base.new)
rails_template.tilt.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Template
  def initialize(string)
    @string = string
  end
  
  def render(object)
    compile
    @object.instance_eval(&@proc)
  end
  
  def compile
    return if @proc
    
    @proc = eval <<-RUBY
proc do
# actual compiled code
end
RUBY
  end
end
 
Template.new(template_string).render(ActionView::Base.new)