Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]

This commit is contained in:
Pratik Naik 2008-11-19 19:36:42 +05:30
parent 51a19ae2bf
commit 51730792ca
3 changed files with 40 additions and 0 deletions

View File

@ -1,5 +1,7 @@
*2.3.0 [Edge]* *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] * 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] * TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing]

View File

@ -71,4 +71,17 @@ class Object
def acts_like?(duck) def acts_like?(duck)
respond_to? "acts_like_#{duck}?" respond_to? "acts_like_#{duck}?"
end 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 end

View File

@ -247,3 +247,28 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase
[arg] + instance_exec('bar') { |v| [reverse, v] } } [arg] + instance_exec('bar') { |v| [reverse, v] } }
end end
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