Last active
November 25, 2016 23:10
-
-
Save kofigumbs/35f59169992a6889f0ad2c0663c2fb87 to your computer and use it in GitHub Desktop.
Ruby Results
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
args = # something | |
Result.try { f(args) } | |
.and_then { |f_output| g(f_output) } | |
.finally( | |
success: proc { |g_output| rended :view }, | |
failure: proc { |error| flash[:error] = error.to_s } | |
) |
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
class Result | |
def self.try(&failable) | |
new(nil).and_then(&failable) | |
end | |
def and_then(&failable) | |
Result.new(failable.call(arg)) | |
catch error | |
Failure.new(error) | |
end | |
def finally(success: proc {}, failure: nil) | |
success.call(arg) | |
end | |
private | |
attr_reader :arg | |
def initialize(arg) | |
@arg = arg | |
end | |
end | |
class Failure | |
def initialize(error) | |
@error = error | |
end | |
def and_then | |
self | |
end | |
def finally(success: nil, failure: proc {}) | |
failure(error) | |
end | |
private | |
attr_reader :error | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is used on line 7. It's initialized to
nil
since the firstResult
in the chain, won't need to use it.