From 65ab56bb188350c8d15931072939b8b6b7bdff63 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Wed, 15 Jul 2009 12:09:22 +0200 Subject: AS guide: documents with_options --- .../guides/source/active_support_overview.textile | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'railties') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index 1537877c18..b6168f84da 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -277,6 +277,45 @@ The method +Hash#to_query+ accepts an optional namespace for the keys: # => "user%5Bid%5D=89&user%5Bname%5D=John+Smith" +h4. +with_options+ + +The method +with_options+ provides a way to factor out common options in a series of method calls. + +Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in: + + +class Account < ActiveRecord::Base + has_many :customers, :dependent => :destroy + has_many :products, :dependent => :destroy + has_many :invoices, :dependent => :destroy + has_many :expenses, :dependent => :destroy +end + + +this way: + + +class Account < ActiveRecord::Base + with_options :dependent => :destroy do |assoc| + assoc.has_many :customers + assoc.has_many :products + assoc.has_many :invoices + assoc.has_many :expenses + end +end + + +That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this: + + +I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n| + subject i18n.t :subject + body i18n.t :body, :user_name => user.name +end + + +TIP: Since +with_options+ forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own. + h4. Silencing Warnings, Streams, and Exceptions The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards: -- cgit v1.2.3