fesplugas (owner)

Fork Of

Revisions

gist: 228261 Download_button fork
public
Public Clone URL: git://gist.github.com/228261.git
Embed All Files: show embed
mustache/rails.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
require "mustache"
 
ActiveSupport::Dependencies.load_paths << Rails.root.join("app", "views")
 
class Mustache::Rails < Mustache
  include ActionController::UrlWriter
  include ActionView::Helpers
 
  attr_accessor :request, :response, :params, :controller
 
  # ActionView::Helpers overrides the +render+ method, so we need to copy it
  # back from Mustache. Ugly, I know :(
  def render(html, context = {})
    @context = context = (@context || {}).merge(context)
    html = render_sections(html)
    @context = context
    render_tags(html)
  end
 
  # Use rails' html_escape ("h") for escaping.
  alias_method :escape, :html_escape
end
 
class Mustache::Rails::TemplateHandler < ActionView::TemplateHandler
  def render(template, local_assigns)
    mustache_class_name = template.path.gsub(".html.mustache", "").classify
    mustache_class = mustache_class_name.constantize
 
    result = mustache_class.new
    copy_instance_variables_to(result)
    result.template_file = Rails.root.join("app", "views", template.path)
    result.controller = @view.controller
    result.request = result.controller.request
    result.response = result.controller.response
    result.params = result.controller.params
    result.to_html
  end
 
  def copy_instance_variables_to(mustache)
    variables = @view.controller.instance_variable_names
    variables -= %w(@template)
    variables -= @view.controller.protected_instance_variables if @view.controller.respond_to?(:protected_instance_variables)
    variables.each {|name| mustache.instance_variable_set(name, @view.controller.instance_variable_get(name)) }
  end
end
 
ActionView::Template.register_template_handler(:mustache, Mustache::Rails::TemplateHandler)