Last active
June 7, 2019 15:20
-
-
Save Drowze/c75e628af6b8185c3b3cb8203dbd6b0d to your computer and use it in GitHub Desktop.
composition operator fun (using ruby 2.7 preview 1)
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 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 |
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
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