Created
November 19, 2008 21:56
-
-
Save nakajima/26751 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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