rails/jbuilder — pull request #15 by joshmcarthur (2012-01-27 23:00:23+00:00)
Title: Use args.size in preference to args.one? for setting single JSON key/value

During our use of JBuilder, a myself and @karmakillernz have observed a bug where if a key is set with a nil value, the entire line is removed from the JSON result - for example:

``` ruby
require 'jbuilder'
json = Jbuilder.encode do |json|
json.title "Hello World"
json.content nil
end

JSON.parse(json) # Yields => {"title": "Hello World"}
```

This problem only occurs when Jbuilder's method_missing method is called with a 'key' and a single 'value'. The problem lies in how the [one? method](http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-one-3F) interprets an array with a nil value - returning false, even though in this case an array with a nil value still represents a JSON value that should be set.

Our solution was to replace the call to `one?` with a simple check that the length of the args passed into `method_missing` is exactly 1. This means that the case..when statement matches correctly, and the key/value pair is correctly added to the output JSON, even when the value is nil.

We have included a test that demonstrates the passing behavior.