class Midnight::Rails::ActiveRecordInteractor

noinspection RubyParameterNamingConvention

Public Class Methods

new( aggregate_key:, build_aggregate:, transaction_handler: Commons::NULL_EVENT_HANDLER, committed_handler: Commons::NULL_EVENT_HANDLER, command_validator: DEFAULT_COMMAND_VALIDATOR, state_persistence: StateAdapter.new( active_record: DefaultState ), advance_state_metadata: lambda(&:advance_metadata), save_state: lambda(&:save!) ) click to toggle source
# File lib/midnight/rails/active_record_interactor.rb, line 9
def initialize(
  aggregate_key:,
  build_aggregate:,
  transaction_handler: Commons::NULL_EVENT_HANDLER,
  committed_handler: Commons::NULL_EVENT_HANDLER,
  command_validator: DEFAULT_COMMAND_VALIDATOR,
  state_persistence: StateAdapter.new(
    active_record: DefaultState
  ),
  advance_state_metadata: lambda(&:advance_metadata),
  save_state: lambda(&:save!)
)
  @aggregate_key = aggregate_key
  @build_aggregate = build_aggregate
  @transaction_handler = transaction_handler
  @committed_handler = committed_handler
  @command_validator = command_validator
  @state_persistence = state_persistence
  @advance_state_metadata = advance_state_metadata
  @save_state = save_state
  freeze
end

Public Instance Methods

call(*commands) click to toggle source
# File lib/midnight/rails/active_record_interactor.rb, line 32
def call(*commands)
  commands.each(&@command_validator)
  transaction do |aggregate|
    commands.each(&aggregate.method(:dispatch))
    aggregate.pending_events
  end
end

Private Instance Methods

transaction(&aggregate_operator) click to toggle source
# File lib/midnight/rails/active_record_interactor.rb, line 42
def transaction(&aggregate_operator)
  @state_persistence.transaction do
    state_record = @state_persistence.load(
      key: @aggregate_key
    )
    aggregate = @build_aggregate.call(
      state: state_record.state
    )
    state_metadata = state_record.metadata
    pending_events = aggregate_operator.call(aggregate)
    @transaction_handler.call(
      pending_events,
      state_metadata
    )
    @state_persistence.hook_commit do
      @committed_handler.call(
        pending_events,
        state_metadata
      )
    end
    state_record.state = aggregate.state
    @advance_state_metadata.call(state_record, pending_events)
    @save_state.call(state_record)
    pending_events
  end
end