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.
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 either display a Model, a Decorator or a Presenter. There is almost no logic in them. Logic should live in the Decorator or Presenter.
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 gather data from multiple models and process it into an understandable data structure.