I’ve been working on a JSON API for mobile clients recently, and in doing so I’ve realised how much you need to repeat serialisation options throughout Rails applications despite options generally being model specific.
This little patch solves that problem by allowing you to decorate your Rails models with model-wide serialisation options, like so:
ActiveRecord model with class-level serialisation options defined
This means that whenever you call to_json or to_xml on an instance of Article, you’ll get the comment association thrown in for you. You’ll find you can clean up your Controllers and remove explicit calling of to_json, which previously would have looked like this:
Defining serialisation options every time to_json is called
While it’s very simple, some people might find it useful. If you do, chuck this in your /lib directory and require it in RAILS_ROOT/config/environment.rb.
Allow class-level definition of serialisation options