Skip to content

Instantly share code, notes, and snippets.

@heisters
Created April 24, 2009 17:17
Show Gist options
  • Save heisters/101219 to your computer and use it in GitHub Desktop.
Save heisters/101219 to your computer and use it in GitHub Desktop.
a more succinct implementation of Object#try
# Makes it easy to try more than one method on Object and just return nil if
# the Object doesn't respond to any of the methods. So, rather than:
#
# obj.try(:foo).try(:bar)
#
# you can just
#
# obj.try(:foo, :bar)
#
# Based on Object#try from ActiveSupport.
class Object
def try *methods
methods.inject(self) do |target, method|
break unless target.public_methods.include? method.to_s
target.send method
end
end
end
describe "Object#try" do
before :each do
@test = Class.new do
def public_method
'value 1'
end
private
def private_method
'value 2'
end
end.new
end
it "should return the result if all methods exist" do
@test.try(:public_method, :size).should == 7
end
it "should return nil if any of the methods don't exist" do
@test.try(:public_method, :doesnt_exist).should be_nil
end
it "should return nil if any of the methods aren't public" do
@test.try(:private_method, :length).should be_nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment