rails/jbuilder — pull request #43 by nbeyer (2012-05-05 02:51:26+00:00)
Title: API to coax the encoding of null values for arrays of JSON objects

With my current understanding of the Jbuilder API, there's no means for creating the following JSON -
```JSON
{"people":[{"name":"Bob Tables"},null,{"name":"Jim Pools"}]}
```

For example, the following snippet encodes an empty JSON object instead of null.
```RUBY
require 'jbuilder'

people = [{fn:"Bob", ln:"Tables"}, nil, {fn:"Jim", ln:"Pools"}]

json = Jbuilder.encode do |json|
json.people(people) do |json, person|
if person
json.name "#{person[:fn]} #{person[:ln]}"
end
end
end

puts json
```
This example outputs the following -
```JSON
{"people":[{"name":"Bob Tables"},{},{"name":"Jim Pools"}]}
```

The attached code adds an additional 'null!' method, which can be used to indicate that a null encoding is desired instead. The above example could then be tweaked to this -
```RUBY
require 'jbuilder'

people = [{fn:"Bob", ln:"Tables"}, nil, {fn:"Jim", ln:"Pools"}]

json = Jbuilder.encode do |json|
json.people(people) do |json, person|
if person
json.name "#{person[:fn]} #{person[:ln]}"
else
json.null!
end
end
end

puts json
```
This example outputs the following -
```JSON
{"people":[{"name":"Bob Tables"},null,{"name":"Jim Pools"}]}
```

The API is slightly awkward and I'm not too sure about the implementation, so I'm open to comments and suggestions on a better approach. Just let me know and I rework it.