<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ent="http://www.purl.org/NET/ENT/1.0/" version="2.0">
  <channel>
    <title>Curiouser and Curiouser! on json</title>
    <link>http://matt.blogs.it/</link>
    <description>RSS feed for topic json</description>
    <copyright>Copyright 2008 Matt Mower. Some rights reserved.</copyright>
    <generator>Squib/0.5.0.382</generator>
    <managingEditor>self@mattmower.com</managingEditor>
    <webMaster>self@mattmower.com</webMaster>
    <language>en-gb</language>
    <item>
      <title>Rendering synthetic JSON</title>
      <link>http://matt.blogs.it/entries/00002938.html</link>
      <pubDate>Thu, 27 Nov 2008 15:18:00 +0000</pubDate>
      <description>&lt;p&gt;Rails has a neat &lt;code&gt;to_json&lt;/code&gt; method you can use for output JSON, so you can quite easily do something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;format.json do
  render :json =&amp;gt; @contents.to_json( :only =&amp;gt; [:id,:title] )
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and Rails will dutifully output the right thing for you.&lt;/p&gt;

&lt;p&gt;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?&lt;/p&gt;

&lt;p&gt;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 &lt;code&gt;playlist.json.erb&lt;/code&gt; file was another possibility but it sucked to need to do that when all I really wanted to do was say:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@contents.to_json( :synthetic =&amp;gt; lambda { |record| gen_synth_attr( record ) } )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;DHH was suggesting to use a decorator class which gets the job done:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@contents.collect { |m| Decorator.new(m) }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Here's what I've ended up with:&lt;/p&gt;

&lt;script src="http://gist.github.com/29766.js"&gt;&lt;/script&gt;

&lt;p&gt;Rather than monkey patching I include &lt;code&gt;Reeplay::ExtendedSerialization&lt;/code&gt; into my models that I use this way. Here's an example use:&lt;/p&gt;

&lt;script src="http://gist.github.com/29768.js"&gt;&lt;/script&gt;

&lt;p&gt;This lets me duck defining a template or polluting my model for such simple extension.&lt;/p&gt;</description>
      <guid isPermaLink="true">http://matt.blogs.it/entries/00002938.html</guid>
      <ent:cloud ent:href="http://matt.blogs.it/topics/">
      </ent:cloud>
    </item>
  </channel>
</rss>
