Last active
August 29, 2015 14:01
-
-
Save rafael/a1bd95e097de22f23b87 to your computer and use it in GitHub Desktop.
Issue with Maybe
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
| # 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>' |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]