Created
May 8, 2015 23:25
-
-
Save brainopia/bc44a298d829ec2d4e63 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
# This class is used to render jbuilder templates in grape. | |
# | |
# There is an existing grape-jbuilder gem but it depends | |
# on tilt-jbuilder gem which | |
# - does not support partial! with :collection | |
# - does not support template compilation | |
# | |
# In constrast this template handler supports all features of jbuilder | |
# and uses template compilation (5x-10x times faster than without). | |
class Tilt::Jbuilder < Tilt::Template | |
class Context < SimpleDelegator | |
def render(options) | |
render_partial options | |
end | |
end | |
def prepare | |
end | |
def file | |
File.join options.fetch(:view_path, '.'), super | |
end | |
def render(scope=Object.new, locals={}) | |
options[:scope] = scope | |
locals[:jbuilder] = self | |
super | |
end | |
def render_partial(options={}) | |
partial = options[:partial].sub /\w+$/, '_\0.jbuilder' | |
builder = Tilt::Jbuilder.new partial, @options.merge(partial: true) | |
builder.render @options[:scope], options[:locals] | |
end | |
def precompiled_preamble(_) | |
<<-RUBY | |
#{super} | |
json ||= JbuilderTemplate.new(Tilt::Jbuilder::Context.new jbuilder) | |
RUBY | |
end | |
def precompiled_template(_) | |
data | |
end | |
def precompiled_postamble(_) | |
'json.target!' unless options[:partial] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment