Tweaking Hash#to_json
I've been struggling with this one the whole day. In my Rails 2.3.5 app, I had a bunch of custom code which allowed the following to happen:
>> strip_hash_keys_for_json({ "a" => 1 }).to_json
=> "{ a: 1 }"
So you see that string keys don't get quoted. It was implemented by creating a String
descendant class that returned self
from to_json
, and all of the hash keys were wrapped in this class.
Today I've started upgrading the app to Rails 3, and it has stopped working, since the JSON-encoding stuff had been rewritten quite seriously.
As you may probably know, in Rails 3 creating a JSON representation of a hash involves two methods:
as_json
which determines what elements of the hash should be present in JSONencode_json
which actually returns a string representation containing the JSON
I figured that I can change the way things happen by observing what encode_json
does, and tweaking some methods that get called from there.
The problem is that these two methods don't get called at all. I've checked for every stupid mistake I could make开发者_如何学JAVA in my investigations and I can see nothing wrong. Google is of no help too, so I turn to the SO fellows for assistance.
Thanks a lot.
UPDATE
OK so I figured out that in order for these methods to work I have to use ActiveSupport::JSON::encode
directly instead of to_json
. This seems weird because
I thought {}.to_json
is handled by the Object#to_json
method defined in that same encoding.rb
file, which in turn calls ActiveSupport::JSON.encode(self, options)
.
Now I'm totally confused.
What happens when you remove the strip_hash_keys_for_json ?
I opened up a console and got:
ruby-1.8.7-p249 > Rails::VERSION::STRING
=> "2.3.5"
ruby-1.8.7-p249 > { "a" => 1 }.to_json
=> "{\"a\":1}"
精彩评论