Passing Options In Roar-Rails Now Works! And Representable Got New Lambdas.

A “recent release”: of representable made it very easy to pass user options like the @current_user@ into the representer.

Basically, you can do things like

@song.to_json(current_user: current_user)

and use those dynamic user options in your representer.

module SongRepresenter
  include Representable::JSON
  property :rating, getter: lambda { |opts| 
    opts[:current_user].rate(self) }

See how you can inject data from outside?

h3. User Options In Roar-Rails.

This now also works with “roar-rails”:, too! Update to 0.0.13 and feel the ease of passing options to @#respond_with@.

class SongsController < ApplicationController
  def show
    respond_with @song, user: current_user

As usual, this works both ways, for rendering and parsing. @#consume!@ also accepts options now.

class SongsController < ApplicationController
  def create
    consume!, user: current_user

Injecting dynamic runtime data into your representers is no longer a pain in “roar-rails”:. Several people already reported “how useful this new feature is”: Thanks!

h3. Overriding Read And Write In Representable.

In “representable”: 1.3.5 we got two new options @:reader@ and @:writer@ for overriding the compilation of the document and parsing a property from an incoming document.

Using the @:writer@ option gives you access to the entire compiled document (e.g. a hash or a @Nokogiri::Node@). The lambda also has access to the user options, if there were any passed.

property :title, writer: lambda do |doc, args| 
  doc["title"] = title || original_title

As you can see it’s up to you as the lambda author to fill in the necessary fragments into the document – representable won’t do it for you when using the @:writer@ option.

This is especially helpful when you need to decide the document key – like @”title”@ – at runtime.

The same works for parsing using @:reader@!

property :title, reader: lambda do |doc, args| 
  self.title = doc["title"] || doc["name"]

Here, it’s your job to assign whatever property you extract from the incoming document. Useful when a property needs to be computed from different fields.

Those features were requested from users in the growing roar/representable community. Thanks for the feedback!


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