Module: RailsEventSourcing::Command

Extended by:
ActiveSupport::Concern
Defined in:
lib/rails-event-sourcing/command.rb

Overview

The Base command mixin that commands include.

A Command has the following public api.

  MyCommand.call(user: ..., post: ...) # shorthand to initialize, validate and execute the command
  command = MyCommand.new(user: ..., post: ...)
  command.valid? # true or false
  command.errors # +> <ActiveModel::Errors ... >
  command.call # validate and execute the command

call will raise an ActiveRecord::RecordInvalid error if it fails validations.

Commands including the RailsEventSourcing::Command mixin must:

  • list the attributes the command takes
  • implement build_event which returns a non-persisted event or nil for noop.

Ex:

  class MyCommand
    include RailsEventSourcing::Command

    attributes :user, :post

    def build_event
      Event.new(...)
    end
  end

Instance Method Summary collapse

Instance Method Details

#call ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'lib/rails-event-sourcing/command.rb', line 73

def call
  return nil if event.nil?
  raise "The event should not be persisted at this stage!" if event.persisted?

  validate!
  execute!

  event
end

#event ⇒ Object

A new record or nil if noop



84
85
86
# File 'lib/rails-event-sourcing/command.rb', line 84

def event
  @event ||= (noop? ? nil : build_event)
end

#noop? ⇒ Boolean

Returns:

  • (Boolean)


88
89
90
# File 'lib/rails-event-sourcing/command.rb', line 88

def noop?
  false
end