Skip to content

Instantly share code, notes, and snippets.

@kofigumbs
Last active November 25, 2016 23:10
Show Gist options
  • Save kofigumbs/35f59169992a6889f0ad2c0663c2fb87 to your computer and use it in GitHub Desktop.
Save kofigumbs/35f59169992a6889f0ad2c0663c2fb87 to your computer and use it in GitHub Desktop.
Ruby Results
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 }
)
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
@kofigumbs
Copy link
Author

kofigumbs commented Jun 29, 2016

Is used on line 7. It's initialized to nil since the first Result in the chain, won't need to use it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment