From 29ce39e217fc3be7efc1f591002bb0b0b9b8a8e9 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 13 Jul 2009 00:07:13 +0200 Subject: AS guide: documents Object#try --- .../guides/source/active_support_overview.textile | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'railties') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index e7751b32b1..23fdd708a2 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -102,6 +102,32 @@ end See also +Object#returning+ in "Extensions to All Objects FIX THIS LINK":FIXME. +h4. +try+ + +Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. + +For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+: + + +def log_info(sql, name, ms) + if @logger && @logger.debug? + name = '%s (%.1fms)' % [name || 'SQL', ms] + @logger.debug(format_log_entry(name, sql.squeeze(' '))) + end +end + + +You can shorten that using +Object#try+. This method is a synonim for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as: + + +def log_info(sql, name, ms) + if @logger.try(:debug?) + name = '%s (%.1fms)' % [name || 'SQL', ms] + @logger.debug(format_log_entry(name, sql.squeeze(' '))) + end +end + + h4. +metaclass+ -- cgit v1.2.3