Last active
August 29, 2015 14:16
-
-
Save nwjsmith/4d74397691019cd070db to your computer and use it in GitHub Desktop.
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 Optional | |
private_class_method :new | |
def self.maybe(possible) | |
possible.nil? ? absent : of(possible) | |
end | |
def self.absent | |
None.new | |
end | |
def self.of(value) | |
raise ArgumentError if value.nil? | |
Some.new(value) | |
end | |
class None | |
def or(default) | |
default | |
end | |
def empty? | |
true | |
end | |
def present? | |
false | |
end | |
def transform(&block) | |
self.class.new | |
end | |
end | |
class Some | |
def initialize(value) | |
@value = value | |
end | |
def or(_default) | |
@value | |
end | |
def empty? | |
false | |
end | |
def present? | |
true | |
end | |
def transform(&block) | |
Optional.maybe(yield @value) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment