Skip to content

Instantly share code, notes, and snippets.

@tjmw
Last active February 6, 2018 08:57
Show Gist options
  • Save tjmw/526f316f75d7a5ab3bbfa76f73439992 to your computer and use it in GitHub Desktop.
Save tjmw/526f316f75d7a5ab3bbfa76f73439992 to your computer and use it in GitHub Desktop.
Experiment in Result#and_then in Ruby
class Result
def initialize(operation, failure_test, *args)
@operation = operation
@failure_test = failure_test
@args = args
end
def and_then(next_operation)
if failure_test.call(result)
self
else
Result.new(next_operation, failure_test, result)
end
end
def result
@result ||= operation.call(*args)
end
private
attr_reader :args, :failure_test, :operation
end
def failure
puts "failure"
{ error: "Something went wrong" }
end
def success
puts "success"
{ ok: 1 }
end
def increment(value)
puts "increment"
{ ok: value[:ok] += 1 }
end
puts Result.new(proc { success }, proc { |resp| resp.key?(:error) }).
and_then(proc { |val| increment(val) }).
and_then(proc { |val| increment(val) }).
and_then(proc { failure }).
and_then(proc { |val| increment(val) }).
result
@tjmw
Copy link
Author

tjmw commented Feb 6, 2018

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