Skip to content

Instantly share code, notes, and snippets.

@Drowze
Last active June 7, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drowze/c75e628af6b8185c3b3cb8203dbd6b0d to your computer and use it in GitHub Desktop.
Save Drowze/c75e628af6b8185c3b3cb8203dbd6b0d to your computer and use it in GitHub Desktop.
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