Created
September 9, 2019 13:37
-
-
Save al3rez/e0c8d3b19e99c0185c686f41b891109e to your computer and use it in GitHub Desktop.
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
module Failable | |
class Result < SimpleDelegator | |
def initialize(success, object = nil) | |
@success = success | |
super(object) | |
end | |
def success? | |
@success | |
end | |
def failure? | |
!@success | |
end | |
end | |
class Failure < StandardError | |
attr_reader :object | |
def initialize(object = nil, message = nil) | |
super(message) | |
@object = object | |
end | |
end | |
def self.included(klass) | |
klass.extend(ClassMethods) | |
end | |
def fail!(object = nil) | |
self.class.fail!(object) | |
end | |
module ClassMethods | |
def call(*args) | |
Result.new(true, new(*args).call) | |
rescue Failure => failure | |
Result.new(false, failure.object) | |
end | |
def fail!(object = nil) | |
fail Failure, object | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment