Rendering synthetic JSON
Rails has a neat to_json method you can use for output JSON, so you can quite easily do something like this:
format.json do
render :json => @contents.to_json( :only => [:id,:title] )
end
and Rails will dutifully output the right thing for you.
In my case though we're building an API for integrating with some 3rd party hardware and we wanted to put some synthetic attributes into the JSON to make it easier for them. How to do this?
Adding attributes to the model didn't seem appropriate since the information was related to this integration in this controller. We could have added singleton methods to the model instances but that looked ugly. Writing a playlist.json.erb file was another possibility but it sucked to need to do that when all I really wanted to do was say:
@contents.to_json( :synthetic => lambda { |record| gen_synth_attr( record ) } )
DHH was suggesting to use a decorator class which gets the job done:
@contents.collect { |m| Decorator.new(m) }
So I was in for defining my own serializer anyway, I felt if it was worth doing that it must be worth trying to make it nicer.
Here's what I've ended up with:
Rather than monkey patching I include Reeplay::ExtendedSerialization into my models that I use this way. Here's an example use:
This lets me duck defining a template or polluting my model for such simple extension.

