You are following the “Fat Models, Skinny Controller” pattern in Rails. Your controllers being the HTTP endpoints are nice and clean. Short action methods and brief assignments. However, your models keep growing and growing, you are losing track of its responsibilities and you are trying to figure out why.

That is a problem. Rails makes you push all your domain code into the persistance layer. Avoiding the oh so dreaded “over-abstraction”, bloating a handful of ActiveRecord classes seems to be a better strategy. Also, the idea of three – and only three – possible places for your business logic makes it easy to justify the growing model: Controllers must be “skinny” and views shouldn’t contain logic, so… if not pushing into the “model”, where else should I put it?

To make it short: Stop thinking in database tables and relations and start modeling your domain with dedicated classes and instances – that is what object-orientation was made for!

What Is My Domain?

If your concern is “I want to export a series of chat messages to a JSON document” then write a new class MessagesDocument. That is your domain. That is the problem you as the programmer are supposed to solve. So do it.

class MessagesDocument
  def to_json(messages)
    messages.collect do |msg|
      msg.to_json
    end.to_json
  end
end

We all know that this simple example will soon get bloated with code lines since we want a little message filter here and a special formatting method for dates there. So, why would you put all this logic into the Message class? It has nothing to do with your message domain at all. And, no, this ain’t no over-engineering, this reflects your concern of compiling a document.

— UPDATE: There was some discussion whether “compiling JSON” is part of “the” domain or not. Well, let’s presume we’re designing a document management tool for librarians (very interesting people, BTW!). In order to send archived files to other systems, one feature is an exporter to serialize documents to JSON – then this component is surely part of your domain.

And, The Persistance Layer?

Strictly speaking, your Message class should be responsible only for synchronizing the model instance with the corresponding row in the database. It is a persistance layer. And this layer should be free of business code. I know, it is handy to simply push in a formatter method for the created_at field – at the cost of an ever-growing class, thou. Think about it. How many methods could you move to dedicated new classes since those behaviours don’t need persistance?

But Isn’t That Over-Engineered?

If Rails and its legendary “model” layer would be good practice, I wouldn’t see dozens of projects all over the world with model files having 600 LOC each, including programmers complaining about too many responsibilites in their classes, starring at me, eyes wide open, blearily, asking where to put all that code. Rails does allow you additional assets, but the framework itself doesn’t answer those questions.

Your fat models are killing your software design. Do you know how hard it is to figure out the concern of a set of methods in a fat class? Of course you do! So why don’t you just generously push a set of logically associated methods into its own class? If that hurts too much you can still move it back into your all-mighty “model”.

What Do We Get From That?

Please don’t get me wrong – I don’t tell you to perfectly abstract your code “Java-like” (hate that comparison) into twohundredseventyfive classes. Relax, and refactor your code step by step. Parts that do not necessarily need the persistance should be separated. You will keep track of what happens where more easily with your refactorings and have faster tests that might encourage you to assert more edge cases.

In addition, that process makes you think about interfaces – the interaction of your new classes with your existing models. Interfaces are a good thing. Don’t fear the class. Hopefully, the next posts in this series can help. I want to talk about mass-assignment problems, lifecycle callbacks in ActiveRecord, form objects, and a lot more including ways to do that practically.

Several speakers were talking about the same problem: Unbloat your models in Rails and focus on your domain instead. “There’s something in the water.” – that was the conclusion of the LoneStar RubyConf 2012 last weekend, a fantastic conference in beautiful Austin, TX with even more fantastic people.

I ran into a problem recently, one of my gems is using Mongoid in tests and all at sudden, Mongoid 3.0 wouldn’t support Ruby 1.8.7 anymore. My builds on Travis broke since I test my gem against 1.8.7 and 1.9.3. So, what I needed was to tell the 1.8 test to use a different Gemfile. Here’s what I did.

I configured the matrix in my .travis.yml file according to the manual.

matrix:
  include:
    - rvm: 1.8.7
      gemfile: gemfiles/Gemfile.mongoid-2.4
    - rvm: 1.9.3
      gemfile: Gemfile

The Gemfile for 1.9.3 is straight-forward.

source :rubygems
 
gemspec

The modified gemfiles/Gemfile.mongoid-2.4 requires the older mongoid version.

source :rubygems
 
gemspec :path => '../'
 
gem 'mongoid', '~> 2.4.0'

Now, my tests run with both Ruby versions both using their own Gemfile. Awesome, Travis!

Rails comes with a massive amount of helpful gems. Those gems are part of Rails’ success and they make Rails the most versatile framework in the Ruby world.

No longer shall using those gems be limited to a Rails environment! The new Cells 3.8.5 allows using many gems in any project, from simple scripts to Sinatra applications, without the Rails dependency. Beside actionpack, no other Rails gem is required.

Let’s see how the great gem simple_form can be used in a Ruby script.

The Gemfile.

For demonstration purpose I want to pass a real ActiveRecord model to simple_form. That is why the Gemfile might look bloated at first sight.

source :gemcutter
 
gem "cells" , "~> 3.8.5"
gem "sqlite3"
gem "activerecord"
gem "simple_form"

The New Module.

If you’re not familiar with Cells yet, check this post. The cell we’re writing is pretty straight-forward with two new lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'cell/base'
require "cell/rails/helper_api"
require "simple_form"
 
class MusicianCell < Cell::Base
  include Cell::Rails::HelperAPI
 
  self._helpers = RoutingHelpers
 
  def show
    @musician = Musician.find(:first)
  end
end

First, note that we use Cell::Base to derive from since we don’t want the Rails dependency (line 5). We then include the module necessary to provide the helpers outside of Rails (line 6).

How Does URLs Work?

Most gems rely on routing helpers. For instance, simple_form is using polymorphic routes helpers like musician_path to compute URLs. Naturally, outside of Rails we don’t have those routes and need to provide them ourselves. This is what happens in line 8.

8
  self._helpers = RoutingHelpers

The corresponding RoutingHelpers module now is up to you.

module RoutingHelpers
  def musician_path(model, *args)
    "/musicians/#{model.id}"
  end
end

Using simple_form In The View.

The state view sitting at musician/play.html.erb might use simple_form now. And, hey, you are not limited to ERB. Cells comes with all the template engines that Rails supports. Use HAML if you fancy. Use Slim to loose weight. Or Whatever.

<%= simple_form_for @musician do |f| %>
  <%= f.input :name %>
  <%= f.button :submit %>
<% end %>

See how easy that is?

The Ruby Script.

Now using all that is as simple as any other steps. This example is just a Ruby script – note that the following code could also be in a Sinatra action, a Webmachine resource, a mailer or whatever you prefer.

require 'musician_cell'
 
MusicianCell.append_view_path(".")
puts Cell::Base.render_cell_for(:musician, :play)

This is enough to render the form with simple_form.

<form accept-charset="UTF-8" action="/musicians/1" class="simple_form edit_musician" id="edit_musician_1" method="post">
  <div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="_method" type="hidden" value="put" /></div>
	<div class="input string optional"><label class="string optional" for="musician_name">Name</label><input class="string optional" id="musician_title" maxlength="255" name="musician[title]" size="50" type="text" value="Steve" /></div>
	<input class="button" name="commit" type="submit" value="Update Musician" />
</form>

Cool, isn’t it?

Using Cells Caching.

If you want to use Cells caching you just have to provide a cache store. You may use any ActiveSupport compatible cache store here, no limits!

cache = ActiveSupport::Cache::MemoryStore.new
 
Cell::Base.render_cell_for(:musician, :play) do |c|
  c.cache_configured = true
  c.cache_store = cache
end

See how we use dependency injection now to configure the cell? This makes the whole workflow completely encapsulated and clean. We might provide some utility methods in the near future to make this setup a little bit more convenient. Let me know what you need. Shap!

Hi everyone, just wanted to give you a quick update. As always, we were hard-working – several versions of representable were released in the last weeks, we even got featured on Ruby5, yo! Here’s what changed.

Nil Properties Are Ignored

In 1.2, uninitialized properties or properties explicitely set to nil are no longer considered when rendering a representation or parsing an incoming document.

Let’s use the same old song example. Sing along, everybody!

class Song
  attr_accessor :name
end
 
module SongRepresenter
  include Representable::JSON
  property :name
end

First, I create a Song instance and extend it with the representer module.

song = Song.new.extend(SongRepresenter)

An uninitialized name will now result in an empty property since the nil property is skipped when rendering.

song.to_json
#=> {}

But I Want The Nil!

You may explicitely tell representable to include nil properties in representations using the new option :render_nil as discussed in this thread.

module SongRepresenter
  include Representable::JSON
  property :name, :render_nil => true
end

Check how the uninitialized (or, nil) is included now.

song.to_json
#=> {"name":null}

Parsing Became Ignorant.

Another change was introduced in parsing. Properties that are not found in the incoming document are ignored, it is up to the represented object to handle with that.

song.from_json("{}")
#=> #<Song:0x8a5145c>

Note how the @name instance variable is not even created. Beware that this might break your API. In former versions, non-existent properties were initialized with nil in the parsing process. That no longer happens!

False Values Are Included, Now!

One consequence is that false values now get a meaning and are included in rendering and parsing.

song.name = false
song.to_json #=> {"name":false}

To summarize, representable got a little bit dumber. nil or non-existant values are simply skipped. You may include them using :render_nil. False values are treated just like any other “valid” property.

Representing Hashes in XML.

A cool newly added feature is the AttributeHash for XML when you want to map a hash to a single XML tag with attributes. Check this example.

require "representable/xml/hash"
 
module SongHashRepresenter
  include Representable::XML::AttributeHash
  self.representation_wrap= :song
end

Rendering is just as simple as calling to_xml.

{:name => "Roxanne", :artist => "The Police"}.
  extend(SongHashRepresenter).to_xml
 
#=> <song name="Roxanne" artist="The Police"/>

Now that is cool. And it works the other way, too!

{}.extend(SongHashRepresenter).
  from_xml('<song name="Roxanne" artist="The Police"/>')
 
#=> {"name"=>"Roxanne", "artist"=>"The Police"}

That is heavily utilized in the roar gem, I will blog about it separately.

More Changes?

Yeah, we replaced the :except option with :exclude as it is more consistent. Who came up with that :except bs at all???

Hope you’re enjoying our little changes – have a nice day!

Yo! How’s it folks? Let’s do some more REST today. I’d like to show how easy it is to have paginated REST documents with Roar while using a nifty feature introduced in version 0.10.2.

What’s In That Fruit Salad, Sir?

Since we keep having fruit salads in the last posts I wanna write a service to display the ingredients of a particular fruit bowl in a list. Not just a list of fruits, a paginated list of fruits.

Let’s GET it.

POST http://bowls/1/fruits?page=1

Considering two fruit items per page this document will be returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{"total_entries":5,
 "links":[
  {"rel": "self",
   "href":"http://bowls/1/fruits?page=1"},
  {"rel": "next",
   "href":"http://bowls/1/fruits?page=2"}],
 "items":[
  {"title":"Apple",
   "links":[{"rel":"self",
              "href":"http://fruits/Apple"}]},
  {"title":"Orange",
   "links":[{"rel":"self",
             "href":"http://fruits/Orange"}]}
  ]
}

Ignore the items for now, the interesting part here are the pagination elements in the first lines. What we have here is:

  • The number of total ingredients in the bowl (line 1).
  • The obligatory self link (line 3-4).
  • A link guiding us to the next page (line 5-6).

Wow! Code?

The backing code in this service endpoint could look like the following snippet. As always, the code used to create this example can be found on github.

1
2
3
4
5
6
bowl = Bowl.find(1)
page = bowl.fruits.paginate(:page => 1, 
  :per_page => 2)
 
page.extend(BowlPageRepresenter)
page.to_json(:bowl => @bowl)

First task is to retrieve the viewed bowl (line 1). I use a static id in this example, feel free to replace it with something like params[:id] in your code. Next, I use paginate from the famous will_paginate gem to get a paged subset of the included fruits. Again, the :page parameter should be refering to a variable, whatever (line 2-3).

Then I simply extend the collection (line 5) since it is a valid Ruby object and call to_json to render the list (line 6). Keep in mind that we pass the :bowl instance into the render method as an argument.

The Bowl Representer Can Do Pagination

To fully understand that example we need to look at the representer now.

module BowlPageRepresenter
  include Roar::Representer::JSON
  include Roar::Representer::Feature::Hypermedia
 
  property :total_entries
  collection :items, :extend => FruitRepresenter
 
  link :self do |opts|
    bowl_url(opts[:bowl], :page => current_page)
  end
 
  link :next do |opts|
    bowl_url(opts[:bowl], :page => next_page) \
      if next_page
  end
 
  link :previous do |opts|
    bowl_url(opts[:bowl], :page => previous_page) \
      if previous_page
  end
 
  def items
    self
  end
end

Instead of refering to line number I’ll use code excerpts now. Do you like that better?

  property :total_entries

In a paginated collection we got the total_entries method as described in the will_paginate API docs. To give our REST consumer a hint about the total amount of ingredients we can simply define a property after that.

  collection :items, :extend => FruitRepresenter

To render the actual items in the doc we extend each fruit with the FruitRepresenter as we learned in an older post. Note that Roar will use the items method to retrieve the collection of fruits.

  def items
    self
  end

Since we are already a collection all we have to do is return self – roar will iterate the paginated collection, extend each element with the FruitRepresenter and render the items.

A Cool New Feature!

The links to the next pages are defined using Roar’s hypermedia feature.

  link :next do |opts|
    bowl_url(opts[:bowl], :page => next_page) \
      if next_page
  end

Two things happen here. First, note that this link is conditional. If next_page, another API method for a will_paginate collection, is evaluated to false, this link won’t be rendered.

Second, we use a new feature of Roar here to access variables passed into to_json. Remember how we called the render method?

page.to_json(:bowl => @bowl)

Right, we pass in some values from the outside since we don’t have access to the actual bowl instance within the represented collection. These parameters are accessible in the link block parameters. Isn’t that nice? I like it.

These few lines of code make it easy to render a paginated collection into a valid REST document.

Writing A Generic Pagination Representer

Now that all paginated documents share attributes (total entries, next and previous link, the self link, etc) why not abstract that into a generic representer? Most of the code can be reused.

module PaginationRepresenter
  include Roar::Representer::JSON
  include Roar::Representer::Feature::Hypermedia
 
  property :total_entries
 
  link :self do |opts|
    page_url(opts[:model], :page => current_page)
  end
 
  link :next do |opts|
    page_url(opts[:model], :page => next_page) \
      if next_page
  end
 
  link :previous do |opts|
    page_url(opts[:model], :page => previous_page) \
      if previous_page
  end
 
  def items
    self
  end
 
  def page_url(*)
    raise "Implement me."
  end
end

All I did was calling a generic page_url method that must be implemented by the using representer. Also, I no longer use the :bowl keyword but a more generic :model, ok?

Nothing in this abstract representer module is related to stinky fruit salads anymore. Man, this thing could even represent a sixpack of beers (a domain I do prefer over fruits).

To inherit we just include the abstract into the concrete representer.

module BowlPageRepresenter
  include Roar::Representer::JSON
  include PaginationRepresenter
 
  collection :items, :extend => FruitRepresenter
 
  def page_url(*args)
    bowl_url(*args)
  end
end

That is cool. All we have to do is defining the concrete items collection and how to compute the pagination URLs. Come on guys, that is easy!

Remember, we changed the incoming parameter, so the rendering call must change, too.

page.to_json(:model => @bowl)

Cheers!

It is Friday eve, have a wonderful weekend and let me know how it was!

Have you ever heard of coercion? Me neither. Anyway, people kept asking for coercion support in roar so I found out that coercion means converting strings into ruby types. Tireless I added a new feature with a whopping 3 lines of code – the cool thing is that this module marries roar with a nifty coercion gem called virtus by my good friend Piotr Solnica.

All you have to do is using the latest roar release (0.10.1), use the appropriate feature and the :type option.

class ImmigrantSong
  include Roar::Representer::JSON
  include Roar::Representer::Feature::Coercion
 
  property :composed_at, :type => DateTime, 
    :default => "May 12th, 2012"
end

This will automatically convert the composed_at property to a decent DateTime object when parsing a document. Note the working :default option, too!

document = "{\"composed_at\":\"November 18th, 1983\"}"
song = ImmigrantSong.new.from_json(document)
song.composed_at #=> 1983-11-18T00:00:00+00:00

The underlying virtus gem takes care of all the conversion work. Note that virtus also automatically adds accessors to the class.

First World Problems

A caveat is that this currently works with inline representers in classes, only. This is cause virtus doesn’t work within modules, yet. I guess we can expect a refactored virtus within days, right, solnic? As soon as this is working in virtus, you can savely use the conversion feature in modules, too. I keep you in the loop!

Oh, I forgot to thank Alex Coles who made me aware of the simplicity of combining those two gems!

A number of users (hundreds, maybe thousands) have been asking why representers are called representers and not “representations”. It is a valid question and since I spent decades to come up with this term I’d like to discuss the decision here quickly.

What Is A Representation?

A representation in the REST style – and this is what we’re talking about here – is a document describing a resource. Actually, it is illustrating the current state of that resource, usually with property/value lists, embedded resources and pointers to other resources using hypermedia. The format is not relevant in this context, it could be JSON, HTML or the accursed XML.

It is a document you can pull on your hard disk, save it and pop it out on christmas again. Did I mention that I’m writing this post in a cafe facing the beach with a cold Castle in my hand, blinded by the sun and intrigued to jump back into the waves?

What Is A Representer?

Now, on the other side, we have the representers as introduced by the roar gem. Those guys are Ruby code and out in the wild you might find them written as modules, mostly. A representer may look like the following beautiful snippet.

module FruitRepresenter
  include Roar::Representer::JSON
 
  property :title
 
  link :self do
    fruit_url(self)
  end
end

In short, injected into an object that very instance gets capable of rendering a document from its current state and updating its attributes by parsing a document – following the syntax definition from the representer module.

Isn’t That A Presenter?

Ok. A representer module enhances an object by enriching it with new methods. Isn’t that a presenter, that’s what Jason wants to know.

The idea seems interesting, but I’m confused as to how this is different from a traditional presenter or decorator?

What I learnt from the tech panel OOP vs. Rails at the fantastic Wroclove.rb conference – if I listened to Steve Klabnik correctly – is

  • Decorator is a pattern that adds methods and optional state to an object. If I write a module introducing currency conversion methods into a float object it’s a Decorator.
  • Presenter seems to be a subset of Decorator which adds functionality for, well, presenting the object. That could be an ActiveRecord row instance extended with methods to serialize to JSON.

Steve, is that true?

So why is a representer not a presenter? Well, the answer is: it is a presenter, but it is more. The rendering behaviour as found in e.g. to_json in the representer is clearly presentation logic. However, the parsing mechanics are definitely beyond the scope of a Presenter. I agree that a representer still is a Decorator (adding functionality, great).

Why Isn’t It Called Representation?

People are worried about the “ter” ending (as in Terminater). Scott got justified concerns that choosing “representer” as opposed to “representation” has roots in my Ruby hipster attitude.

So, if “Representer” is a reflection of the popularity of “Presenter”,it would seem to be an example of throwing good money after bad. If “Presenter” is already somewhat tainted with inaccuracy, then so would “Representer”.

In an email he is refering to that confusion caused by the Presenter pattern name in the Ruby community (just google presenter + ruby if you can’t follow now). So his proposal

The Fruit class is a “Representation”, not a representer.

Oh no, call it representation!

And as if that wasn’t enough critics on MY pattern name, Charles Lowell, author of rubyracer, saviour of the poor and knight of the dark, reinforces the representation argument.

personally I prefer FooRepresentation as opposed to FooRepresenter, but that’s just me. It implies that “this defines what the representation is“, as opposed to “This defines is how the representation is generated”

That sounds conclusive to me and lead me to reflecting the terms once again.

Now What, Representer or Representation?

So, maybe the the concrete representation declaration (the module using roar and defining properties and hyperlinks) is a representation whereas the underlying abstracted module is a representer?

I speaking for myself still prefer the name representer as we not only define syntax and semantic of a representational document but also add functionality to the represented object as it gets enriched with e.g. to_json and from_json. That as-it makes the FruitRepresenter module “active” and justifies the “ter” ending, just as in “Terminater”, ok?

Just a quick round-up for new things in the Roar world. Here we go!

Roar Speaks JSON-HAL Now!

In the last Ruby on REST post I explained the basics of the hypermedia type HAL which gives your document nesting and linking semantics. This promising format is now supported by Roar.

By including the Representer::JSON::HAL module in your representer it will render and parse documents according to the HAL standard.

module OrderRepresenter
  include Roar::Representer::JSON::HAL
 
  property :id
  collection :items,
    :class => Item, 
    :extend => ItemRepresenter,
    :embedded => true
 
  link :self do "http://orders/#{id}" end
end

Links will now be pushed into the _links property. Also note the new :embedded option which will key the nested property under _embedded. And all that just by including a module – that’s the power of representers.

Better Links in JSON

Some users asked for another link format when not using the HAL representer. Usually links are handled like this.

"links":[
  { "rel":  "self", 
    "href": "http://orders/42"},
  { "rel":  "items", 
    "href": "http://orders/42/items"}
]}

This is just a format I came up with when writing Roar. Now, if you include Representer::JSON::HAL::Links in your representer, links will be rendered and parsed a bit different.

"links": { 
  "self":  {"href": "http://orders/42"}, 
  "items": {"href": "http://orders/42/items"}
}

Here, links is a hash keyed by rel – very handy on the client side.

Also, you can now include more attributes in links.

link :rel => :self, :title => "That's me!"

Just provide a hash listing the attributes.

Representable Got Conditional Properties!

Last but not least, representable, the underlying mapping gem of Roar got a new option in the 1.1.6 release. :if allows you to define blocks that are evaled when parsing or rendering (“representing”, yo!) the object. If the proc returns false, the property is ignored.

property :state, :if => lambda { authorized? }

The block is executed in instance context allowing you to access instance methods and whatever else you need. Go for it!

Let me start this post by quoting something smart.

REST [is an] architectural style for distributed hypermedia systems”

That actually is the first line, chapter 5 of Roy Fielding’s thesis about REST. I gave a couple of talks last year about hypermedia and the misunderstandings in REST in the Rails world and this post tries to sum up with that by focusing on the hypermedia aspect of this architectural concept.

Challenge: Make Fruit Salad!

In the last posts we discussed using the Roar gem for designing and implementing REST systems in Ruby. We were using fruits and bowls as an exemplary domain – let’s keep up with that and fix a fruit salad today.

As a first step it makes sense getting a bowl for all the ingredients. In our REST system, we just POST to the bowls URL.

POST http://bowls
Content-type: application/json
------------------------------
{"location": "desk"}

The request body contains a minimal document specifying the location for the created bowl. Here’s what we get back.

{"location":"desk",
 "fruits":[],
 "links":[
  {"rel":"self",  "href":"http://bowls/desk"},
  {"rel":"fruits","href":"http://bowls/desk/fruits"}
]}

By reading this I figure out that the bowl on my desk was created, but doesn’t contain any fruits, yet. Also, these “links” seem understandable, while self might point to the bowl resource itself the fruits link probably directs to a collection resource listing all the ingredients in that very bowl.

Looks as if a URL gets a “meaning” by specifying a rel attribute with it.

I infered all that by intuition, as JSON is a pretty simple representation format. And this is the first problem when trying to understand hypermedia. JSON as it doesn’t include any semantics, the links are, well, useless as they’re not understandable to machines. What we need is a hyper-media type. Get it on!

What Is A Media Type, Sir?

A concept called media type gives both syntax and semantics to a document. It is important to understand that a simple media type like JSON doesn’t define anything. It just provides a medium (or format) to encode information.

Why not put it that way: JSON and XML are like primitive communication mechanics. Where XML uses smoke signals for exchanging messages, JSON is human voice. A poor example.

However, listening to my voice doesn’t mean you understand what I’m saying. Reading JSON is like listening to my sounds, but the noize might not make sense to you. Ok?

The media type is like a language. You understanding the media type “english” and me speaking (JSON) in english (media type) makes us happy chatters. And suddenly, a series of sounds turn into “Would you like another beer?”. You understand me since you know the syntax and the semantics of my sounds. That is a media type!

Now That We Understand Hypermedia, What To Do With It?

Instead of using plain, dumb JSON I’d like to introduce a real hypermedia format called HAL which is “specifically for exposing RESTful hypermedia APIs”.

POST http://bowls
Content-type: application/hal+json
------------------------------
{"location": "desk"}

Note that we used the application/hal+json content type desparately hoping the web service understands this media format. Check the response.

{"location":"desk",
 "_embedded":{"fruits":[]},
 "_links":{
  "self":  {"href":"http://bowls/desk"},
  "fruits":{"href":"http://bowls/desk/fruits"}
}}

It obviously does, and now the links are encoded a little bit different, following the HAL standard. While this doesn’t make a real difference for you human being, it changes a lot in machine context. By using this media format, we added semantics: Now, the HAL-aware client knows that links can be found at the _links key, that they’re keyed by rel and so on.

Think about it briefly. Growing up with human voice you understood JSON before. However, now that you learned HAL, you understand all the bits and pieces in the document just by applying the specification rules.

I’m Still Hungry!

Sorry for that detailed discussion about hypermedia types, I’m really getting hungry as well, so let’s add some fruits to the bowl.

POST http://bowls/desk/fruits
Content-type: application/hal+json
------------------------------
{"title": "Apple"}

An apple a day keeps the doctor away. Assuming it is sufficient to post this mini JSON document to the fruits URL I add an apple to my salad. Did that work?

GET http://bowls/desk
Content-type: application/hal+json
------------------------------
{"location":"desk",
 "_embedded":{
  "fruits":[
   {"title":"Apple",
    "colors":[],
    "_links":{"self":{"href":"http://fruits/apple"}}
  }]  
 "_links":{
  "self":  {"href":"http://bowls/desk"},
  "fruits":{"href":"http://bowls/desk/fruits"}}
}

Yeah! I can see an apple inside the _embedded key, which is HAL’s way to nest resources in representations. Also, the apple contains a link again pointing to its resource.

It is needless to note that I could go on like this and POST more fruits to the fruits collection resource in order to enrich my delicious salad.

What Did I Just Do?

This brief example was brief. Nevertheless, it demonstrated the use of hypermedia. Here’s what I did.

  1. First, I POSTed to http://bowls to create a bowl.
  2. The returned document points me to its fruits resource.
  3. To add fruits, I POST to http://bowls/desk/fruits as defined in the representation.
  4. I retrieve the updated bowl by following the self URL of the bowl.

Well, what’s so special about that?

The key is, I didn’t compute any URL except the initial URL in (1.) – this is what we call the single entry point. No knowledge about follow-up URLs was needed to operate my fruit salad API. Everything I need to know is included in the representations.

Actions (aka URLs) that are meaningful in the current application state can be found in the document without any need to build URLs myself. This concept is called HATEOAS – a beautiful name… for a cat.

Thou Shall Not Make Any Fruit Salad Without Hypermedia!

Roy Fielding, the inventor of REST, states that your API is RESTFUL if and only if it is hypermedia-driven! In my words, that’ll mean no URL code should be hard-wired into your REST client – except for the single entry point URL. Any additional resource must be extracted from returned documents. And, hey, this is the very reason why REST is defined as a style for “distributed hypermedia systems”.

How that works with the Roar gem is subject to discussion in my upcoming next post! Stay tuned and enjoy life!

Do you remember when we were writing a reusable sidebar element some time ago? The sidebar used in many controllers was implemented using a cell which encapsulated both assets and code in one place. Those were good times.

When needed, we could render the box with a render_cell call anywhere in our app.

#sidebar
  = render_cell :posts, :recent

Reusability With Engines

Now, imagine this sidebar box was so universally usable that you wanna use it in another project. Code is usually distributed with gems in a Ruby environment – but how does that work with partials, helpers, view code?

We got engines in Rails. We got Cells. We got gems. So let’s pack the cell in an engine gem!

Engines were designed to distribute controllers, views and models between Rails projects. As an example, lots of the authorization gems around use engines for reusable login pages or password reset forms that can be used right in your project. There was no easy way for reusing partials and behaviour, though, unless you’re using cells.

The Cell, Gemified.

In order to ship the sidebar posts box I first need to create a Rails engine.

$ rails plugin new sidebar --mountable

This creates a distributable directory with all the files needed to mount it into a Rails app.

As a second step we need to move the PostsCell into that gem.

$ mv app/cells/posts sidebar/app/cells/

You can now include the sidebar gem in any application using the Gemfile.

gem 'sidebar', :path => 'vendor/plugins/sidebar'

To render your reusable component, just use the render_cell call as you did in the originating application.

Conclusion

Damn, this conclusion came fast, but there is really not more to say. Oh, did I mention that you should update to Cells 3.8.3 for full engines support in Rails 3.0, 3.1 and even 3.2?!

Cells + Engines bring real reusability to Rails. It’s da shit.