Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Playing around with a Bottom object and try operator.
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