Roar-Rails 0.1 Released – Namespacing Done Right.

Just recently, we released “roar-rails 0.1.0”: Hooray. While making it run smoothly with Rails 4, we made @::represents@ a little bit smarter: representer names are infered better and now support namespaces.

h3. Represents.

You can use roar-rails without configuring it.

class SongsController  SongRepresenter

In @respond_with@, roar-rails will use the passed model’s class to infer the representer name. When rendering a collection, however, the controller name is the base for computation, resulting in a pluralized @SongsRepresenter@.

h3. Namespacing.

This convention worked well but led to some confusion when controllers were namespaced. Whatever, in 0.1, the representer will always be namespaced (if your controller is namespaced, of course).

module V1
  class SongsController < ApplicationController

Both rendering and consuming will infer @V1::SongRepresenter@ and @V1::SongsRepresenter@ by convention. This might break your existing code, as entity representers weren’t namespaced automatically.

Roar-rails only adds namespaces when it _infers_ representer names. That means, when you explicitly specify a name, it will use this and don’t do any maths leaving it up to you.

h3. Configuration Over Convention.

If you’re unhappy with roar-rails’ conventions, you can tell it to behave appropriate with @represents@.

module V1
  class SongsController < ApplicationController
    represents :json, Song

    def show
      respond_with Evergreen.find(1)

This will always use @V1::Song@ as the base and not check the rendered or parsed model’s class, resulting in @SongRepresenter@ even you passed in an @Evergreen@ instance.

class SongsController < ApplicationController
  represents :json, entity:     V2::SongRepresenter,
                     collection: V1::SongsRepresenter

Using the @:entity@ and @:collection@ options you can fine-tune which representer to choose. Note that you don’t have to specify both, e.g. if you’re not interested in collections. Who needs collections, anyway?

If you want to compute the representer ad-hoc at run-time, use @:represent_with@.

respond_with @song, 
  :represent_with => V1::EvergreenRepresenter

h3. Consumption.

Note that the techniques described above work both ways, for @respond_with@ rendering and @consume!@ to parse incoming documents.

module V1
  class SongsController  V1::EvergreenRepresenter

I hope this slightly changed behaviour (spelled the english way as I am in Australia now) gives you a convenient way for using namespaces.


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 )

Google+ photo

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

Connecting to %s