The Presenter Pattern is a way to compose a single unified object that can be utilized to properly output data for a specific purpose. Utilizing these in Rails has been[pdf] covered many times before. Today, let’s go over about using them as a solution to the problems that many are experiencing with the limitations of ActiveRecord’s built in as_json functionality available in Rails.
Setting The Stage
If you are creating a versioned API, you might have namespaced routes and controllers that look like…
Api::V1::ResourceController < Api::V1::BaseController
This setup allows you to namespace your API controllers and isolate code across API versions. If as_json is being utilized solely, change isolation across API response versions will likely degrade quickly. We can add presenters namespaced identically to our controllers to alleviate this problem.
To begin, let’s add a “presenters” directory inside of “app” along with a directory structure that matches our namespacing e.g. “app/presenters/api/v1”. Since we are focusing on RESTful APIs, our presenters will most likely match our models. This is an important distinction as it let’s us version what would normally be in our as_json method in the model.
Say we had another resource that has a one-to-one relationship to original resource. Here's an example of what its presenter might look like…
Lastly, in our controller, we could setup a method that looks like the following…
This implementaiton yields flexibility, customization, and testability instead of ActiveRecord’s as_json rigidity. We can now setup presenters for our models and utilize them in our controllers to provide the desired structure of our JSON responses. It might be a little rough around the edges, but seems promising.
What do you think?