The Dread Comma
Consider the following scrap of code from a Rails helper method:
hash = { :id => result.id, :title => result.name, :addr => result.foo } hash[:foo] = controller.send(:render_to_string, {:partial => "foo", :object => hash}), hash.merge!(more_params(result)) hash.to_json
That code raises a JSON::CircularDatastructure exception. Here is the corrected code:
hash = { :id => result.id, :title => result.name, :addr => result.foo } hash[:foo] = controller.send(:render_to_string, {:partial => "foo", :object => hash}) hash.merge!(more_params(result)) hash.to_json
The difference is a single comma at the end of the fourth line. Without that comma, the code works as expected. In sequence, a literal hash is declared, an additional key-value pair is added, and a hash returned by a method call is merged in. With the comma, however, hash[:foo] is set to a two-element array. The first element is what we intended and the second is the hash itself, creating a recursive (a.k.a. circular) data structure. I am too embarassed to admit how long it took me to figure out what was going on.
Forewarned, may you never encounter such a bug in your own code. Enjoy!
1 Comments:
At 5/12/2007 01:51:00 PM, Anonymous said…
There is no way for the Ruby Lexical parser to know that your comma in that place is typo :).
Post a Comment
<< Home