Module: Eventsimple::Entity

Defined in:
lib/eventsimple/entity.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Constant Summary collapse

DEFAULT_IGNORE_PROPS =
%w[id lock_version].freeze

Instance Method Summary collapse

Instance Method Details

#event_driven_by(event_klass, aggregate_id:, filter_attributes: []) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/eventsimple/entity.rb', line 7

def event_driven_by(event_klass, aggregate_id:, filter_attributes: [])
  begin
    if table_exists? && !column_names.include?(locking_column)
      raise ArgumentError, "A #{locking_column} column is required to enable eventsimple on this model."
    end

    if defined?(event_klass._aggregate_id) && event_klass.table_exists? && table_exists?
      raise ArgumentError, "aggregate_id mismatch event:#{event_klass._aggregate_id} entity:#{aggregate_id}" if aggregate_id != event_klass._aggregate_id

      aggregate_column_type_in_event = event_klass.column_for_attribute(:aggregate_id).type
      aggregate_column_type_in_entity = column_for_attribute(aggregate_id).type

      raise ArgumentError, "column type mismatch - event:#{aggregate_column_type_in_event} entity:#{aggregate_column_type_in_entity}" if aggregate_column_type_in_event != aggregate_column_type_in_entity
    end
  rescue ActiveRecord::AdapterError
    # skip checks if the database is not yet created
  end

  has_many :events, class_name: event_klass.name.to_s,
    foreign_key: :aggregate_id,
    primary_key: aggregate_id,
    dependent: :delete_all,
    inverse_of: model_name.element.to_sym,
    autosave: false,
    validate: false

  after_initialize :readonly!

  class_attribute :ignored_for_projection, default: []

  class_attribute :_filter_attributes
  self._filter_attributes = [aggregate_id] | Array.wrap(filter_attributes)

  class_attribute :_aggregate_id
  self._aggregate_id = aggregate_id

  # disable automatic timestamp updates
  self.record_timestamps = false

  Eventsimple.configuration.ui_visible_model_names |= [name]

  include InstanceMethods
  extend ClassMethods
end