Permalink
Browse files

Add the template handler back and give it the power to do partial ren…

…ders
  • Loading branch information...
dhh committed Nov 30, 2011
1 parent e288a49 commit 4335842f35b228401944af90b308b00233ab8523
Showing with 31 additions and 10 deletions.
  1. +1 −5 README.md
  2. +1 −1 jbuilder.gemspec
  3. +4 −4 lib/jbuilder.rb
  4. +25 −0 lib/jbuilder_template.rb
View
@@ -68,10 +68,6 @@ You can either use Jbuilder stand-alone or directly as an ActionView template la
end
# You can use partials as well, just remember to pass in the json instance
- render @message.comments, json: json
-
-Jbuilder is included with Rails 3.2 and automatically configured. If you want to use Jbuilder templates with an earlier version of Rails 3, you can add the following code in something like config/initializer/jbuilder_templates.rb:
-
- ActionView::Template.register_template_handler :jbuilder, -> template { "Jbuilder.encode do |json|;#{template.source};end;" }
+ json.partial! "api/comments/comments" @message.comments
Note: Jbuilder is similar to Garrett Bjerkhoel's json_builder, which I discovered after making this, but the DSL has taken a different turn and will retain the explicit yield style (vs json_builder's 3.0's move to instance_eval).
View
@@ -1,6 +1,6 @@
Gem::Specification.new do |s|
s.name = 'jbuilder'
- s.version = '0.2'
+ s.version = '0.3'
s.author = 'David Heinemeier Hansson'
s.email = 'david@37signals.com'
s.summary = 'Create JSON structures via a Builder-style DSL'
View
@@ -7,9 +7,7 @@
class Jbuilder < BlankSlate
# Yields a builder and automatically turns the result into a JSON string
def self.encode
- jbuilder = new
- yield jbuilder
- jbuilder.target!
+ new._tap { |jbuilder| yield jbuilder }.target!
end
define_method(:__class__, find_hidden_method(:class))
@@ -162,4 +160,6 @@ def _yield_iteration(container, collection)
def _inline_extract(container, record, attributes)
__send__(container) { |parent| parent.extract! record, *attributes }
end
-end
+end
+
+require "jbuilder_template" if defined?(ActionView::Template)
View
@@ -0,0 +1,25 @@
+class JbuilderTemplate < Jbuilder
+ def self.encode(context)
+ jbuilder = new(context)
+ yield jbuilder
+ jbuilder.target!
+ end
+
+ def initialize(context)
+ @context = context
+ super()
+ end
+
+ def partial!(partial_name, options = {})
+ @context.render(partial_name, options.merge(json: self))
+ end
+
+ private
+ def _new_instance
+ __class__.new(@context)
+ end
+end
+
+ActionView::Template.register_template_handler :jbuilder, Proc.new { |template|
+ "if defined?(json); #{template.source}; else; JbuilderTemplate.encode(self) do |json|;#{template.source};end; end;"
+}

0 comments on commit 4335842

Please sign in to comment.