Skip to content

Commit

Permalink
Merge pull request #251 from amatsuda/locals
Browse files Browse the repository at this point in the history
partial! + :locals
  • Loading branch information
rwz committed Mar 3, 2015
2 parents baa7a66 + 4c15a08 commit c80f7b2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,17 @@ json.partial! partial: 'posts/post', collection: @posts, as: :post
json.comments @post.comments, partial: 'comment/comment', as: :comment
```

You can pass any objects into partial templates with or without `:locals` option.

```ruby
json.partial! 'sub_template', locals: {user: user}

# or

json.partial! 'sub_template', user: user
```


You can explicitly make Jbuilder object return null if you want:

``` ruby
Expand Down
9 changes: 7 additions & 2 deletions lib/jbuilder/jbuilder_template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ def initialize(context, *args, &block)
def partial!(name_or_options, locals = {})
case name_or_options
when ::Hash
# partial! partial: 'name', locals: { foo: 'bar' }
# partial! partial: 'name', foo: 'bar'
options = name_or_options
else
# partial! 'name', locals: {foo: 'bar'}
if locals.one? && (locals.keys.first == :locals)
options = locals.merge(partial: name_or_options)
else
options = { partial: name_or_options, locals: locals }
end
# partial! 'name', foo: 'bar'
options = { partial: name_or_options, locals: locals }
as = locals.delete(:as)
options[:as] = as if as.present?
options[:collection] = locals[:collection] if locals.key?(:collection)
Expand Down
18 changes: 17 additions & 1 deletion test/jbuilder_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class JbuilderTemplateTest < ActionView::TestCase

def partials
{
'_partial.json.jbuilder' => 'json.content "hello"',
'_partial.json.jbuilder' => 'foo ||= "hello"; json.content foo',
'_blog_post.json.jbuilder' => BLOG_POST_PARTIAL,
'_collection.json.jbuilder' => COLLECTION_PARTIAL
}
Expand Down Expand Up @@ -110,6 +110,22 @@ def assert_collection_rendered(json, context = nil)
assert_equal 'hello', MultiJson.load(json)['content']
end

test 'partial! + locals via :locals option' do
json = render_jbuilder <<-JBUILDER
json.partial! 'partial', locals: {foo: 'howdy'}
JBUILDER

assert_equal 'howdy', MultiJson.load(json)['content']
end

test 'partial! + locals without :locals key' do
json = render_jbuilder <<-JBUILDER
json.partial! 'partial', foo: 'goodbye'
JBUILDER

assert_equal 'goodbye', MultiJson.load(json)['content']
end

test 'partial! renders collections' do
json = render_jbuilder <<-JBUILDER
json.partial! 'blog_post', :collection => BLOG_POST_COLLECTION, :as => :blog_post
Expand Down

0 comments on commit c80f7b2

Please sign in to comment.