Saturday, June 11, 2011

Rails spoiled standard json library

You're screwed if in your rails application you still want to use standard json library, not the rails one. I had to write a small patch to get Rails hands off my jsonified classes.

Here's how STANDARD JSON library works:
1. In your class you need define 2 methods:
to_json and self.json_create
2. Convert to json: json_string = your_instance.to_json
   Parse json: JSON.parse(json_string)

RAILS evil deed
In case of RAILS, the to_json function is hacked(monkey patched) where they call ActiveSupport's json encode.
The evil code is here:
So, this file loads standard json library and then rewrites to_json on all ruby core objects.

SOLUTION. Make converting (to_json) work. This will serialize properly to json.
In your jsonifiable classes additionally to to_json, define as_json function.
def as_json(*a)
          'json_class' =>,
          'a' => json_data

No comments:

Post a Comment