Skip to content

Instantly share code, notes, and snippets.

@alissonbrunosa
Last active February 17, 2020 13:38
Show Gist options
  • Save alissonbrunosa/c9d6c51381025632aa25d015d55986fd to your computer and use it in GitHub Desktop.
Save alissonbrunosa/c9d6c51381025632aa25d015d55986fd to your computer and use it in GitHub Desktop.
def Ok(value)
Okay.new(value)
end
def Err(value)
Error.new(value)
end
class Result
attr_reader :value
def initialize(value)
@value = value
end
def ok?
raise "Not implemented"
end
def error?
raise "Not implemented"
end
def and_then(&block)
raise "Not implemented"
end
def or_else(&block)
raise "Not implemented"
end
def to_s
"#{self.class}(#{value})"
end
end
class Okay < Result
def ok?
true
end
def error?
false
end
def and_then
result = yield(value)
raise TypeError, "block did not return Result instance" unless result.is_a?(Result)
result
rescue StandardError => error
Err(error)
end
def or_else
self
end
end
class Error < Result
def ok?
false
end
def error?
true
end
def and_then
self
rescue StandardError => error
Err(error)
end
def or_else
result = yield(value)
raise TypeError, "block did not return Result instance" unless result.is_a?(Result)
result
rescue StandardError => error
Err(error)
end
end
# Usage
result = UserRepository.find(1)
result
.and_then { |user| DocumentRepository.find_by(user.id) }
.or_else { |error| # do something with error }
# Usage 2
def do_something
# do something here and return a value to result
Ok(result)
rescue StandardError => error
Err(error)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment