Created
April 16, 2012 15:17
-
-
Save danwrong/2399405 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
stream, out = streaming_writer | |
@template.execute(out, context) | |
stream | |
end | |
protected | |
def string_writer | |
java.io.StringWriter.new | |
end | |
def streaming_writer | |
reader = java.io.PipedReader.new | |
writer = java.io.PipedWriter.new(reader) | |
[Stream.new(reader), writer] | |
end | |
end | |
class Stream | |
def initialize(reader) | |
@reader = reader | |
end | |
def each | |
buf = Java::char[1024].new | |
read = 0 | |
while @reader.read(buf) >= 0 | |
yield java.lang.String.new(buf) | |
buf = Java::char[1024].new | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your solution to 1) is much neater, keeping character handling within the java ecosystem.