diff options
author | Pratik Naik <pratiknaik@gmail.com> | 2008-11-19 19:36:42 +0530 |
---|---|---|
committer | Pratik Naik <pratiknaik@gmail.com> | 2008-11-19 19:36:42 +0530 |
commit | 51730792ca930a896361eb92354a42bc56903de1 (patch) | |
tree | da1992628081de9c2c0f09b64e1d55893d6e2bcd /activesupport | |
parent | 51a19ae2bf33e66b23ff5c91bf584b2efa9e669f (diff) | |
download | rails-51730792ca930a896361eb92354a42bc56903de1.tar.gz rails-51730792ca930a896361eb92354a42bc56903de1.tar.bz2 rails-51730792ca930a896361eb92354a42bc56903de1.zip |
Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/CHANGELOG | 2 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/misc.rb | 13 | ||||
-rw-r--r-- | activesupport/test/core_ext/object_and_class_ext_test.rb | 25 |
3 files changed, 40 insertions, 0 deletions
diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 5997b7daaf..0717d344d7 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath] + * Added Enumerable#none? to check that none of the elements match the block #1408 [Damian Janowski] * TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing] diff --git a/activesupport/lib/active_support/core_ext/object/misc.rb b/activesupport/lib/active_support/core_ext/object/misc.rb index cd0a04d32a..50f824c358 100644 --- a/activesupport/lib/active_support/core_ext/object/misc.rb +++ b/activesupport/lib/active_support/core_ext/object/misc.rb @@ -71,4 +71,17 @@ class Object def acts_like?(duck) respond_to? "acts_like_#{duck}?" end + + # Tries to send the method only if object responds to it. Return +nil+ otherwise. + # + # ==== Example : + # + # # Without try + # @person ? @person.name : nil + # + # With try + # @person.try(:name) + def try(method) + send(method) if respond_to?(method, true) + end end diff --git a/activesupport/test/core_ext/object_and_class_ext_test.rb b/activesupport/test/core_ext/object_and_class_ext_test.rb index e88dcb52d5..fbdce56ac2 100644 --- a/activesupport/test/core_ext/object_and_class_ext_test.rb +++ b/activesupport/test/core_ext/object_and_class_ext_test.rb @@ -247,3 +247,28 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase [arg] + instance_exec('bar') { |v| [reverse, v] } } end end + +class ObjectTryTest < Test::Unit::TestCase + def setup + @string = "Hello" + end + + def test_nonexisting_method + method = :undefined_method + assert !@string.respond_to?(method) + assert_nil @string.try(method) + end + + def test_valid_method + assert_equal 5, @string.try(:size) + end + + def test_valid_private_method + class << @string + private :size + end + + assert_equal 5, @string.try(:size) + end + +end |