DRY with_options
ruby activesupport railsOne of the cool features in ActiveSupport
is with_options
.
It helps you remove duplication:
belongs_to :playlist, touch: true, inverse_of: :devices
belongs_to :company, inverse_of: :devices
Will become:
with_options inverse_of: :devices do |a|
a.belongs_to :playlist, touch: true
a.belongs_to :company
end
However, there is one gotcha which was unclear for me after reading apidock.
When using ActiveRecord associations you have to use block variable to define associations like in example above. So this:
with_options inverse_of: :devices do
belongs_to :playlist, touch: true
belongs_to :company
end
Will not work! However, when using validations, delegations, attr_* it’s not required and you can write this:
class User < ActiveRecord::Base
with_options to: :profile, allow_nil: true do
delegate :locale, :email, :gender, :time_zone, :first_name, :last_name
end
with_options presence: true do
validates :login, length: { maximum: 256 }
validates :password
end
end
Conclusion
Use with_options
, but remember to add block variable when using it for ActiveRecord associations.