Last active
February 6, 2018 08:57
-
-
Save tjmw/526f316f75d7a5ab3bbfa76f73439992 to your computer and use it in GitHub Desktop.
Experiment in Result#and_then in Ruby
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This became https://github.com/tjmw/streamlet