Skip to content

Instantly share code, notes, and snippets.

@rafael
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save rafael/a1bd95e097de22f23b87 to your computer and use it in GitHub Desktop.

Select an option

Save rafael/a1bd95e097de22f23b87 to your computer and use it in GitHub Desktop.
Issue with Maybe
# Null Object Pattern:
# http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/
require 'delegate'
RUBY_VERSION # => "2.0.0"
class NullObject
def method_missing(*args, &block)
self
end
def to_a; []; end
def to_s; ""; end
def to_f; 0.0; end
def to_i; 0; end
end
BasicObject.class_eval do
def Maybe(value)
case value
when nil then NullObject.new
else value
end
end
end
Maybe("test") # => "test"
class Foo
def test
Maybe("test")
end
end
class Bazz < SimpleDelegator
def test
Maybe("test")
end
end
a = Foo.new
a.test # => "test"
b = Bazz.new("test")
b.test # => "test" from -:41:in `<main>'
@rafael
Copy link
Author

rafael commented May 6, 2014

Note for the future: This happens because SimpleDelegator doesn't inherits from Object.

a.class.ancestors # => [Foo, Object, Kernel, BasicObject]
b.class.ancestors # => [Bazz, SimpleDelegator, Delegator, #Module:0x000001010243b8, BasicObject]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment