Representable 2.1 Is Faster!

Representable 2.1 has been out for a few weeks now. I haven’t had time to blog due to my book preview release but here we go.


I spend days on figuring out how to speed up Representable. Surprisingly, by removing def_delegators we could improve parsing and rendering performance more than 100%! Instead of using the Ruby delegator, we define the methods manually.

An attempt to introduce binding caches turned out to bring overly complex changes to representable without a note-worthy performance improvement. That’s why it didn’t make it into this release.

Skip Parsing.

An extremely cool new feature is that you can skip parsing for properties and items in collections.

property :title, skip_parse: 
  lambda { |fragment, options| fragment.blank? }

Note how both the fragment and options from the #from_json call are passed into the lambda. If the lambda evaluates to true the property won’t be parsed, as if it hadn’t been present in the incoming document.

The same works with collections: here, the lambda is run for every item. The item is not parsed and not deserialised when the filter applies.

As a side note, this is used in Reform 1.2 to implement skip_if: :all_blank semantics which helps ignoring empty forms.

Skip Rendering.

The same also works the other way round.

property :title, skip_render: 
  lambda { |object, options| options[:skip_title] }

Accessing the options hash means you can implement run-time filters when rendering documents. For instance, this could be used to exclude certain properties from a JSON document when access rights are restricted.

song.to_json(skip_title: Permissions.allow?(:title))

I personally can’t wait to play with this in Trailblazer to allow more dynamic representers in combination with authorization gems.

Debugging – Made Easy!

Even though Representable is very lean and structured it can be hard to understand what is happening in a 5-level nested model. We added Representable::Debug to make just that easier.

Usually, you would inject the debugger into a certain object.


Representable will then start to output what is going on. Feel free to add messages: the debugging simply happens by overriding the original methods, collecting messages and then returning to the actual method.

I hope this will help you writing awesome stuff!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s