Created
July 19, 2012 19:47
-
-
Save avit/3146317 to your computer and use it in GitHub Desktop.
NilObject, much borrowed from avdi.org
This file contains hidden or 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 NilObject | |
def true?; false end | |
def false?; true end | |
def nil?; true end | |
def blank?; true end | |
def present?; false end | |
def empty?; true end | |
def to_s; "" end | |
def !; true end | |
def method_missing(*args, &block) | |
self | |
end | |
def to_value | |
nil | |
end | |
module Confidence | |
def self.included(base) | |
base.extend self | |
end | |
def Maybe(value) | |
case value | |
when nil then NilObject.new | |
else value | |
end | |
end | |
def Actual(object) | |
case object | |
when NilObject then nil | |
else object | |
end | |
end | |
end | |
end |
This file contains hidden or 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 'spec_helper_base' | |
require 'nil_object' | |
class SomeObject | |
include NilObject::Confidence | |
attr_accessor :colour | |
def self.maybe_edible; Maybe(nil) end | |
def maybe_colour; Maybe(colour) end | |
def actual_colour; Actual(colour) end | |
end | |
describe NilObject do | |
its(:true?) { should be_false } | |
its(:false?) { should be_true } | |
its(:nil?) { should be_true } | |
its(:blank?) { should be_true } | |
its(:present?) { should be_false } | |
its(:empty?) { should be_true } | |
its(:to_s) { should == "" } | |
it "is true when negated" do | |
(!subject).should be_true | |
(not subject).should be_true | |
end | |
it "returns nil for all chained methods" do | |
subject.foo.bar.baz.should be_nil | |
end | |
end | |
describe NilObject::Confidence do | |
describe "Maybe" do | |
subject { SomeObject.new } | |
it "returns actual value when present" do | |
subject.colour = "blue" | |
subject.maybe_colour.should == "blue" | |
end | |
it "returns a NilObject for nil" do | |
subject.colour = nil | |
subject.maybe_colour.should be_a NilObject | |
end | |
end | |
describe "Actual" do | |
subject { SomeObject.new } | |
it "returns actual value when present" do | |
subject.colour = "red" | |
subject.actual_colour.should == "red" | |
end | |
it "returns actual nil when nil" do | |
subject.colour = nil | |
subject.actual_colour.should be_a NilClass | |
end | |
end | |
describe "class methods" do | |
it "is extended" do | |
SomeObject.maybe_edible.should be_a NilObject | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment