Skip to content

Instantly share code, notes, and snippets.

@nakajima
Created November 19, 2008 21:56
Show Gist options
  • Save nakajima/26751 to your computer and use it in GitHub Desktop.
Save nakajima/26751 to your computer and use it in GitHub Desktop.
class Object
def try(method_id, *args, &block)
respond_to?(method_id) ? send(method_id, *args, &block) : nil
end
end
require 'rubygems'
require 'spec'
describe Object, "#try" do
attr_reader :klass, :object
before(:each) do
@klass = Class.new do
def foo(arg=nil)
block_given? ? yield : (arg || :bar)
end
end
@object = klass.new
end
it "should send when object responds to message" do
object.try(:foo).should == :bar
end
it "should return nil when object doesn't respond to message" do
object.try(:fizz).should be_nil
end
it "should allow args" do
object.try(:foo, :wee).should == :wee
end
it "should allow block" do
object.try(:foo) { :wee }.should == :wee
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment