Let's read some Rails code: with_options
Did you know you can refactor this:
# Duplicated :dependent => :destroy option.
class Account < ActiveRecord::Base
has_many :customers, :dependent => :destroy
has_many :products, :dependent => :destroy
has_many :invoices, :dependent => :destroy
has_many :expenses, :dependent => :destroy
end
into this?
# Better, perhaps.
class Account < ActiveRecord::Base
with_options :dependent => :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
assoc.has_many :expenses
end
end
The with_options
method is a really cool chunk of code that lets you DRY up
duplication that sometimes appear when passing the same options to a series of
methods.
Curious how it works behind the scenes? Check out this 11-minute code walkthrough: