class Object

def with_options(options, &block)


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)
  block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
end