Skip to content

Instantly share code, notes, and snippets.

@tomafro
Forked from danwrong/gist:2399405
Created April 16, 2012 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomafro/2399749 to your computer and use it in GitHub Desktop.
Save tomafro/2399749 to your computer and use it in GitHub Desktop.
module Mustache
class << self
import com.github.mustachejava.DefaultMustacheFactory
import com.github.mustachejava.jruby.JRubyObjectHandler
def template_dir
Rails.root.join('app', 'templates')
end
def factory
@factory ||= begin
factory = DefaultMustacheFactory.new java.io.File.new(template_dir.to_s)
factory.setObjectHandler(JRubyObjectHandler.new)
factory
end
end
def compile(template)
CompiledTemplate.new(factory.compile(template))
end
end
class View < Hash
def self.inherited(subclass)
class << subclass
attr_accessor :template_path
end
subclass.template_path = subclass.name.underscore.gsub(/_view$/, '') + '.html'
end
def initialize(context={})
self.update(context)
end
def render_string
Mustache.compile(self.class.template_path).render_string(self)
end
def render
Mustache.compile(self.class.template_path).render(self)
end
end
class CompiledTemplate
def initialize(template)
@template = template
end
def render_string(context)
out = string_writer
@template.execute(out, context).flush
out.to_s
end
def render(context)
StreamingMustache.new(@template, context)
end
protected
def string_writer
java.io.StringWriter.new
end
class StreamingMustache
def initialize(template, context)
@template = template
@context = context
end
def each(&block)
@template.execute(StreamingWriter.new(&block), @context)
end
class StreamingWriter < java.io.Writer
def initialize(&block)
@block = block
end
java_signature 'void write(char[], int, int)'
def write(chars, offset, length)
string = java.lang.String.new(chars.slice(offset, length))
@block.call(string)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment