DRY up kwargs using `with_options`
Rails has a really awesome helper to DRY up code which makes use of much of the same kwargs. It’s called with_options
and is used like this:
class Account < ActiveRecord::Base
has_many :customers, dependent: :destroy
has_many :products, dependent: :destroy
end
# Becomes this with `with_option`
class Account < ActiveRecord::Base
with_options dependent: :destroy do
has_many :customers
has_many :products
end
end
Your code is now a lil more DRY and its easier to add, or remove, pesky kwargs as needed.
Another quick example:
class AuthenticatedController < ApplicationController
before_action :logged_in?, only: [:show, :edit]
before_action :create_paper_trail, only: [:show, :edit]
# ...
end
# Becomes this with `with_option`
class AuthenticatedController < ApplicationController
with_options only: [:show, :edit] do
before_action :logged_in?
before_action :create_paper_trail
end
# ...
end
Tweet