Created
February 17, 2011 15:47
-
-
Save jimweirich/831947 to your computer and use it in GitHub Desktop.
Playing around with a Bottom object and try operator.
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
require 'rspec/given' | |
class Object | |
def _? | |
self | |
end | |
def _ | |
self | |
end | |
end | |
class Bottom | |
def bottom? | |
true | |
end | |
def method_missing(sym, *args, &block) | |
self | |
end | |
def _ | |
nil | |
end | |
def self.instance | |
@instance ||= Bottom.new | |
end | |
end | |
class NilClass | |
def _? | |
Bottom.instance | |
end | |
end | |
describe "_?" do | |
S = Struct.new(:item) | |
context "with a real object" do | |
Given(:obj) { S.new(1) } | |
When(:result) { obj._?.item } | |
Then { result.should == 1 } | |
Then { result._.should == 1 } | |
end | |
context "with a nil object" do | |
When(:result) { nil._?.item } | |
Then { result.should be_bottom } | |
Then { result._.should be_nil } | |
end | |
context "with a chain of nils" do | |
Given(:obj) { S.new(nil) } | |
When(:result) { obj._?.item._?.item._?.item } | |
Then { result.should be_bottom } | |
Then { result._.should be_nil } | |
end | |
context "with a chain of objects" do | |
Given(:obj) { S.new(S.new(S.new(5))) } | |
When(:result) { obj._?.item._?.item._?.item } | |
Then { result.should == 5 } | |
Then { result._.should == 5 } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment