aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides
diff options
context:
space:
mode:
authorXavier Noria <fxn@hashref.com>2009-07-13 00:07:13 +0200
committerXavier Noria <fxn@hashref.com>2009-07-13 00:07:13 +0200
commit29ce39e217fc3be7efc1f591002bb0b0b9b8a8e9 (patch)
tree33ab8857cefd384ddbe5f4b3a137e1b6a5f2acc7 /railties/guides
parentae44ed59082d7d2c7db32dd93611a16a41c84e13 (diff)
downloadrails-29ce39e217fc3be7efc1f591002bb0b0b9b8a8e9.tar.gz
rails-29ce39e217fc3be7efc1f591002bb0b0b9b8a8e9.tar.bz2
rails-29ce39e217fc3be7efc1f591002bb0b0b9b8a8e9.zip
AS guide: documents Object#try
Diffstat (limited to 'railties/guides')
-rw-r--r--railties/guides/source/active_support_overview.textile26
1 files changed, 26 insertions, 0 deletions
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+:
+
+<ruby>
+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
+</ruby>
+
+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:
+
+<ruby>
+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
+</ruby>
+
h4. +metaclass+