Ruby on Rails code architecture tips

A collection of tips about designing Rails application and making a better architecture.

Split out Fat Models

Split out your Fat Models into Services, Decorators and Presenters
The approach is to put:

– Business Logic into Services

– Human Data into Decorators

– Complex Data Manipulations into Presenters

This will follow the single responsibility principle.

So our Models, Controllers and Helpers really slim.

Ref.

http://reverbhq.com/blog/2012/08/building-web-apps-with-activeadmin/

 

Models

Models are used for data access, persistency and consistency.
Models are slim. They only take care of associations, validations, scopes and a few request & mutating methods.

Views

Views either display a Model, a Decorator or a Presenter. There is almost no logic in them. Logic should live in the Decorator or Presenter.

Controller Actions

The CRUD actions are managed by Active Admin through InheritedResources. Custom actions are delegated to a Service.

Services: Business Logic
A Service implements the Business Logic of the application. It can be tested via Unit or Integration Tests. A Service is likely to rely on ActiveRecord models or other Services.

 

Decorators: One Model Data for Human-Readable Data

A Decorator adds methods for reading by humans to a model.

class UserDecorator < Draper::Base
  decorates :user
 
  def full_name
    [user.first_name, user.last_name].compact.join ' '
  end
end

Presenters

Presenters gather data from multiple models and process it into an understandable data structure.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>