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

{{{
A “recent release”:http://nicksda.apotomo.de/2013/02/representable-1-3-3-released-with-user-options-support/ 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) }
end

See how you can inject data from outside?

h3. User Options In Roar-Rails.

This now also works with “roar-rails”:https://github.com/apotonick/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
  end

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

class SongsController < ApplicationController
  def create
    consume! Song.new, user: current_user
  end

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”:https://twitter.com/ruprictGeek/status/322324674367348736. Thanks!

h3. Overriding Read And Write In Representable.

In “representable”:https://github.com/apotonick/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
end

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"]
end

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!
}}}

Advertisement

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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