Hi everyone, just wanted to give you a quick update. As always, we were hard-working – several versions of representable were released in the last weeks, we even got featured on Ruby5, yo! Here’s what changed.

Nil Properties Are Ignored

In 1.2, uninitialized properties or properties explicitely set to nil are no longer considered when rendering a representation or parsing an incoming document.

Let’s use the same old song example. Sing along, everybody!

class Song
  attr_accessor :name
module SongRepresenter
  include Representable::JSON
  property :name

First, I create a Song instance and extend it with the representer module.

song = Song.new.extend(SongRepresenter)

An uninitialized name will now result in an empty property since the nil property is skipped when rendering.

#=> {}

But I Want The Nil!

You may explicitely tell representable to include nil properties in representations using the new option :render_nil as discussed in this thread.

module SongRepresenter
  include Representable::JSON
  property :name, :render_nil => true

Check how the uninitialized (or, nil) is included now.

#=> {"name":null}

Parsing Became Ignorant.

Another change was introduced in parsing. Properties that are not found in the incoming document are ignored, it is up to the represented object to handle with that.

#=> #<Song:0x8a5145c>

Note how the @name instance variable is not even created. Beware that this might break your API. In former versions, non-existent properties were initialized with nil in the parsing process. That no longer happens!

False Values Are Included, Now!

One consequence is that false values now get a meaning and are included in rendering and parsing.

song.name = false
song.to_json #=> {"name":false}

To summarize, representable got a little bit dumber. nil or non-existant values are simply skipped. You may include them using :render_nil. False values are treated just like any other “valid” property.

Representing Hashes in XML.

A cool newly added feature is the AttributeHash for XML when you want to map a hash to a single XML tag with attributes. Check this example.

require "representable/xml/hash"
module SongHashRepresenter
  include Representable::XML::AttributeHash
  self.representation_wrap= :song

Rendering is just as simple as calling to_xml.

{:name => "Roxanne", :artist => "The Police"}.
#=> <song name="Roxanne" artist="The Police"/>

Now that is cool. And it works the other way, too!

  from_xml('<song name="Roxanne" artist="The Police"/>')
#=> {"name"=>"Roxanne", "artist"=>"The Police"}

That is heavily utilized in the roar gem, I will blog about it separately.

More Changes?

Yeah, we replaced the :except option with :exclude as it is more consistent. Who came up with that :except bs at all???

Hope you’re enjoying our little changes – have a nice day!


Leave a Reply