Skip to content

Instantly share code, notes, and snippets.

@nwjsmith
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjsmith/4d74397691019cd070db to your computer and use it in GitHub Desktop.
Save nwjsmith/4d74397691019cd070db to your computer and use it in GitHub Desktop.
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