Rails patterns & best practices

Table of Contents

a summary of the courses rails 4 patterns and the older rails best practices (rails 3) by code school, as well as some additional material.

1 models

  1. only use callbacks for manipulating internal state, no tight coupling with other models
  2. set callbacks as protected
  3. avoid "god objects": anti pattern because it violates Single Responsibility Principle
  4. not everything needs to be database backed -> encapsulate business logic out of DB backed models; also useful for proper REST architecture.
  5. keep serialization out of controllers by using ActiveModel::Serializers (point Gemfile entry to GitHub repo)
  6. use pluck method if you don't need AR objects (also see Getting to Know Pluck and Select by Gavin Miller)
  7. ActiveSupport::Memoizable was deprecated in Rails 3.1; use ||= or memoist
  8. if you use them a lot, also index columns you order by
  9. if possible set default values in database, not in a filter
  10. use bullet gem to find N+1 queries and other performance issues
  11. use size with counter caches
  12. do batch processing with find_each
  13. user delegate to avoid Law of Demeter violations
  14. use to_param for friendly URLs

2 controllers

  1. ask object to perform an action, don't query its internal state (business logic -> model)
  2. uses scopes in model instead of logic in controller (also see default_scope and unscoped)
  3. use merge method to merge scopes instead of duplicating conditions (last scope wins in case of shared column)
  4. filter sensitive parameters from logs by using config.filter\_parameters in config/application.rb
  5. good examples for filters: authorization, logging, wizards
  6. use presenters to avoid complex controller actions
  7. use the new responder syntax (respond_to class method + respond_with)

3 views

  1. no queries in views!
  2. don't use instance variables in partials, use locals instead
  3. use nested layouts when all actions of a controller renders into a content_for

4 general

  1. avoid duplication by using concerns (see Put chubby models on a diet with concerns by dhh)
  2. use decorators for view-related business logic (app/decorators)
  3. specify ruby version in Gemfile
  4. use foreman for Procfile-backed apps

Author: Michael Kohl

Created: 2014-01-24 Fri 16:01

Emacs 24.3.1 (Org mode 8.2.4)

Validate