rails/jbuilder — pull request #148 by garysweaver (2013-10-08 17:19:55+00:00)
Title: nil-collection should be treated as empty array in template

I noticed that when I passed in a nil as an empty collection in a template, it did not treat as an empty collection, although a nil-collection was already treated as an empty array in one place already in JBuilder:

```ruby
json.array! @posts, partial: 'posts/post', as: :post
json.partial! 'posts/post', collection: @posts, as: :post
json.partial! partial: 'posts/post', collection: @posts, as: :post
json.comments @post.comments, partial: 'comment/comment', as: :comment
```

Without this change, it will use the partial template that will return an error like the following, which is non-obvious:

```
NameError: undefined local variable or method `foo' for <:0x007fc69a6e42f0>
app/views/path/to/partial/_foo.json.jbuilder:1:in `_app_views_path_to_partial__foo_json_jbuilder___82125411139652069_70245417019000'
app/views/path/to/view/index.json.jbuilder:1:in `_app_views_path_to_view_index_json_jbuilder__40707230780250694_70245416948080'
```

Instead of treating a nil collection as an empty array, it could raise `ArgumentError` or similar with a more specific error, but the following seems to go against that a little:

* _map_collection treating nil collection as array [here](https://github.com/rails/jbuilder/blob/7ff4d28c95162f4a9200c05722ae88101aa812bc/lib/jbuilder.rb#L312)

* set! (method_missing handling to allow json.* calls in template) making the assumption [here](https://github.com/rails/jbuilder/blob/7ff4d28c95162f4a9200c05722ae88101aa812bc/lib/jbuilder.rb#L95) that something that doesn't respond to `map` is a single value and not array (which seems to be an accident, so I fixed to look for `:as` option also.

Thanks for considering this change. We can work around it by having nil checks in each template, but I don't think that is as obvious.