class Object
def with_options(options, &block)
# #=>
# styled.button_tag "I'm red too!"
# #=> I'm red
# styled.link_to "I'm red", "/"
end
end
with_options style: "color: red;"
def styled
module MyStyledHelpers
When the block argument is omitted, the decorated Object instance is returned:
end
end
validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys }
with_options presence: true do
enum phone_number_type: { home: 0, office: 1, mobile: 2 }
class Phone < ActiveRecord::Base
You can access these methods using the class name instead:
NOTE: You cannot call class methods implicitly inside of with_options.
Hence the inherited default for +if+ key is ignored.
validates :content, length: { minimum: 50 }, if: -> { content.present? }
The code is equivalent to:
end
end
validates :content, if: -> { content.present? }
with_options if: :persisted?, length: { minimum: 50 } do
class Post < ActiveRecord::Base
NOTE: Each nesting level will merge inherited defaults in addition to their own.
with_options can also be nested since the call is forwarded to its receiver.
end
end
has_many :expenses
has_many :invoices
has_many :products
has_many :customers
with_options dependent: :destroy do
class Account < ActiveRecord::Base
in merging options context:
When you don't pass an explicit receiver, it executes the whole block
end
body i18n.t :body, user_name: user.name
subject i18n.t :subject
I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
It can also be used with an explicit receiver:
end
end
assoc.has_many :expenses
assoc.has_many :invoices
assoc.has_many :products
assoc.has_many :customers
with_options dependent: :destroy do |assoc|
class Account < ActiveRecord::Base
Using with_options, we can remove the duplication:
end
has_many :expenses, dependent: :destroy
has_many :invoices, dependent: :destroy
has_many :products, dependent: :destroy
has_many :customers, dependent: :destroy
class Account < ActiveRecord::Base
Without with_options, this code contains duplication:
hash as its final argument.
provided. Each method called on the block variable must take an options
the receiver, will have its options merged with the default +options+ hash
method calls. Each method called in the block, with the block variable as
An elegant way to factor duplication out of options passed to a series of
def with_options(options, &block) option_merger = ActiveSupport::OptionMerger.new(self, options) if block block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger) else option_merger end end