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) }
end

See how you can inject data from outside?

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
  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. Thanks!

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

One Response to “Passing Options In Roar-Rails Now Works! And Representable Got New Lambdas.”

  1. I was wondering if you ever considered changing the layout of your website?
    Its very well written; I love what youve got to say.
    But maybe you could a little more in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1
    or two pictures. Maybe you could space it out better?

Leave a Reply