carlosbrando (owner)

Fork Of

Revisions

gist: 45258 Download_button fork
public
Public Clone URL: git://gist.github.com/45258.git
Embed All Files: show embed
other try.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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