Create a gist now

Instantly share code, notes, and snippets.

@lackac /2_ways.md
Last active Aug 29, 2015

2 Ways to Decompose Fat ActiveRecord Models – budapest.rb 03/2014

Intro

  • Fat Model, Skinny Controller
  • Object-Oriented Design Patterns
  • Single Responsibility Principle

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

2 Ways to Decompose Fat ActiveRecord Models

Query Object

Purpose: encapsulate complex queries

Benefits:

  • no unwieldy SQL in model
  • keeps benefits of AR scopes

Example

DeliveryOption.current

Service Objects

Purpose: encapsulate complex actions, concerns, or responsibilities that reach across multiple models

Benefits:

  • SRP makes maintenance easier
  • developers know where to go to tweak behavior
  • easier to test
  • tends to make codebase DRYer

Example

active_discount

Further Reading

  • Practical Object-Oriented Design in Ruby, by Sandi Metz
  • Objects on Rails, by Avdi Grim
  • Refactoring: Ruby Edition, by Jay Fields, Shane Harvie, Martin Fowler, Kent Beck

https://www.youtube.com/watch?v=WpkDN78P884 (mentioned in the discussion)

About

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment