Sha256: 222e1c45f27eaaf02809cb2c8bd8fd5302022684db244f2792ff5c3eeb175128

Contents?: true

Size: 1.1 KB

Versions: 3

Compression:

Stored size: 1.1 KB

Contents

module NulogyMessageBusConsumer
  class Pipeline
    def initialize(steps)
      @steps = steps
    end

    def invoke
      convert_steps_into_lambda.call
    end

    def insert(step, after:)
      index = @steps.find_index { |s| s.is_a?(after) }
      @steps.insert(index + 1, step)
    end

    def append(step)
      @steps << step
    end

    private

    def convert_steps_into_lambda
      last_step = ->(**_) { raise "Handlers are the end of the line. Do not use yield." }

      @steps.reverse.reduce(last_step) do |composed_steps, previous_step|
        lambda do |**args|
          invoke_next = compose_with_merged_args(args, composed_steps)
          previous_step.call(**args, &invoke_next)
        end
      end
    end

    def compose_with_merged_args(existing_args, func)
      lambda do |**yielded_args|
        args_to_be_overridden = existing_args.keys & yielded_args.keys
        if args_to_be_overridden.any?
          raise "Cannot override existing argument(s): #{args_to_be_overridden.join(', ')}"
        end

        func.call(**existing_args.merge(yielded_args))
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
nulogy_message_bus_consumer-0.3.3 lib/nulogy_message_bus_consumer/pipeline.rb
nulogy_message_bus_consumer-0.3.2 lib/nulogy_message_bus_consumer/pipeline.rb
nulogy_message_bus_consumer-0.3.1 lib/nulogy_message_bus_consumer/pipeline.rb