class LightService::Organizer::WithReducer

Attributes

context[R]
organizer[RW]

Public Class Methods

call(_context) { || ... } click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 24
def self.call(_context)
  yield
end
new(monitored_organizer = nil) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 7
def initialize(monitored_organizer = nil)
  @organizer = monitored_organizer
end

Public Instance Methods

around_each(handler) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 17
def around_each(handler)
  @around_each_handler = handler
  self
end
around_each_handler() click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 22
def around_each_handler
  @around_each_handler ||= Class.new do
    def self.call(_context)
      yield
    end
  end
end
reduce(*actions) { |current_context, action| ... } click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 30
def reduce(*actions)
  raise "No action(s) were provided" if actions.empty?

  @context.around_actions ||= around_each_handler
  actions.flatten!

  actions.each_with_object(context) do |action, current_context|
    invoke_action(current_context, action)
  rescue FailWithRollbackError
    reduce_rollback(actions)
  ensure
    # For logging
    yield(current_context, action) if block_given?
  end
end
reduce_rollback(actions) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 46
def reduce_rollback(actions)
  reversable_actions(actions)
    .reverse
    .reduce(context) do |context, action|
      if action.respond_to?(:rollback)
        action.rollback(context)
      else
        context
      end
    end
end
with(data = {}) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 11
def with(data = {})
  @context = LightService::Context.make(data)
  @context.organized_by = organizer
  self
end

Private Instance Methods

invoke_action(current_context, action) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 60
def invoke_action(current_context, action)
  if action.respond_to?(:call)
    action.call(current_context)
  else
    action.execute(current_context)
  end
end
reversable_actions(actions) click to toggle source
# File lib/light-service/organizer/with_reducer.rb, line 68
def reversable_actions(actions)
  index_of_current_action = actions.index(@context.current_action) || 0

  # Reverse from the point where the fail was triggered
  actions.take(index_of_current_action + 1)
end