Created
June 14, 2014 08:14
-
-
Save araipiyo/56ee0b202db24e42da66 to your computer and use it in GitHub Desktop.
maybe for Ruby. easier handling of nil. nil is most bothersome thing in Ruby, right?
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 'singleton' | |
class Object | |
def maybe | |
if self.class == NilClass | |
Maybe.instance | |
else | |
self | |
end | |
end | |
end | |
class NilClass | |
def id | |
nil | |
end | |
end | |
class Maybe | |
include Singleton | |
def method_missing(m, *args, &block) | |
self | |
end | |
def respond_to_missing?(*_) | |
true | |
end | |
def inspect | |
"maybe" | |
end | |
def ==(a) | |
if a.class == NilClass | |
true | |
elsif a.class == Maybe | |
true | |
else | |
false | |
end | |
end | |
def id | |
nil | |
end | |
def to_s | |
"" | |
end | |
def to_i | |
0 | |
end | |
def to_f | |
0.0 | |
end | |
def to_a | |
[] | |
end | |
def blank? | |
true | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment