Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
composition operator fun (using ruby 2.7 preview 1)
class SubtractTwoInteraction
def self.call(number)
number - 2
end
end
class MultiplyByInteraction
def self.call(number:, by:)
number * by
end
end
class DivideByInteraction
def self.call(number:, by:)
number / by
end
end
module Workflow # aka Organizer in collectiveidea/interactor gem
def call(*args)
function.call(*args)
end
def function
raise NotImplementedError
end
end
class SimpleWorkflow
extend Workflow
def self.function
SubtractTwoInteraction.:call >>
->(n) { { number: n, by: 2 } } >> # "glue" between two interactions
MultiplyByInteraction.:call
end
end
class ConditionalWorkflow
extend Workflow
def self.function
SubtractTwoInteraction.:call >>
->(n) { { number: n, by: 2 } } >>
->(params) {
klass = params[:number] > 10 ? DivideByInteraction : MultiplyByInteraction
params.then(&klass.:call)
}
end
end
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'minitest', require: false
end
require 'minitest/autorun'
require_relative './compositional_fun'
class WorkflowTest < Minitest::Test
def test_simple_workflow
assert_equal SimpleWorkflow.call(7), 10
end
def test_conditional_workflow
assert_equal ConditionalWorkflow.call(7), 10
assert_equal ConditionalWorkflow.call(13), 5
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment