File: //usr/local/rvm/gems/ruby-3.0.2/doc/activesupport-6.1.4.1/ri/Object/with_options-i.ri
U:RDoc::AnyMethod[iI"with_options:ETI"Object#with_options;TF:publico:RDoc::Markup::Document:@parts[ o:RDoc::Markup::Paragraph; [
I"OAn elegant way to factor duplication out of options passed to a series of ;TI"Omethod calls. Each method called in the block, with the block variable as ;TI"Pthe receiver, will have its options merged with the default +options+ hash ;TI"Mprovided. Each method called on the block variable must take an options ;TI" hash as its final argument.;To:RDoc::Markup::BlankLine o;
; [I"CWithout <tt>with_options</tt>, this code contains duplication:;T@o:RDoc::Markup::Verbatim; [I"(class Account < ActiveRecord::Base
;TI"0 has_many :customers, dependent: :destroy
;TI"0 has_many :products, dependent: :destroy
;TI"0 has_many :invoices, dependent: :destroy
;TI"0 has_many :expenses, dependent: :destroy
;TI" end
;T:@format0o;
; [I"@Using <tt>with_options</tt>, we can remove the duplication:;T@o;; [
I"(class Account < ActiveRecord::Base
;TI"3 with_options dependent: :destroy do |assoc|
;TI"# assoc.has_many :customers
;TI"" assoc.has_many :products
;TI"" assoc.has_many :invoices
;TI"" assoc.has_many :expenses
;TI" end
;TI" end
;T;
0o;
; [I"3It can also be used with an explicit receiver:;T@o;; [ I"JI18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
;TI" subject i18n.t :subject
;TI"2 body i18n.t :body, user_name: user.name
;TI" end
;T;
0o;
; [I"KWhen you don't pass an explicit receiver, it executes the whole block ;TI" in merging options context:;T@o;; [
I"(class Account < ActiveRecord::Base
;TI"+ with_options dependent: :destroy do
;TI" has_many :customers
;TI" has_many :products
;TI" has_many :invoices
;TI" has_many :expenses
;TI" end
;TI" end
;T;
0o;
; [I"Z<tt>with_options</tt> can also be nested since the call is forwarded to its receiver.;T@o;
; [I"UNOTE: Each nesting level will merge inherited defaults in addition to their own.;T@o;; [
I"%class Post < ActiveRecord::Base
;TI"@ with_options if: :persisted?, length: { minimum: 50 } do
;TI"9 validates :content, if: -> { content.present? }
;TI" end
;TI" end
;T;
0o;
; [I"The code is equivalent to:;T@o;; [I"Nvalidates :content, length: { minimum: 50 }, if: -> { content.present? }
;T;
0o;
; [I"9Hence the inherited default for +if+ key is ignored.;T@o;
; [I"LNOTE: You cannot call class methods implicitly inside of with_options. ;TI"?You can access these methods using the class name instead:;T@o;; [I"&class Phone < ActiveRecord::Base
;TI"A enum phone_number_type: { home: 0, office: 1, mobile: 2 }
;TI"
;TI"& with_options presence: true do
;TI"X validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys }
;TI" end
;TI"end;T;
0:
@fileI"7lib/active_support/core_ext/object/with_options.rb;T:0@omit_headings_from_table_of_contents_below000[ I"(options, &block);T@eFI"Object;TcRDoc::NormalClass00