Class: Yes::Core::ProcessManagers::State Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/yes/core/process_managers/state.rb

Overview

This class is abstract.

Subclass and override #stream, #required_attributes, and implement apply_* methods.

Represents the state of a subject loaded in a process manager by replaying events.

Examples:

class UserState < Yes::Core::ProcessManagers::State
  RELEVANT_EVENTS = %w[UserCreated UserUpdated].freeze

  attr_reader :name, :email

  private

  def stream
    PgEventstore::Stream.new(context: 'Users', stream_name: 'User', id: id)
  end

  def required_attributes
    %i[name email]
  end

  def apply_user_created(event)
    @name = event.data['name']
    @email = event.data['email']
  end
end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id) ⇒ State

Returns a new instance of State.

Parameters:

  • id (String, Integer)

    the id of the subject to be loaded



41
42
43
# File 'lib/yes/core/process_managers/state.rb', line 41

def initialize(id)
  @id = id
end

Class Method Details

.load(id) ⇒ State

Loads the state for a given ID.

Parameters:

  • id (String, Integer)

    the id of the subject to be loaded

Returns:

  • (State)

    a new instance with events applied



36
37
38
# File 'lib/yes/core/process_managers/state.rb', line 36

def self.load(id)
  new(id).tap(&:load)
end

Instance Method Details

#loadvoid

This method returns an undefined value.

Loads the state from relevant events.



48
49
50
51
52
53
# File 'lib/yes/core/process_managers/state.rb', line 48

def load
  events = relevant_events(stream)
  return unless events

  process_events(events)
end

#valid?Boolean

Checks if the state is valid (all required attributes are present).

Returns:

  • (Boolean)

    true if all required attributes are present



58
59
60
# File 'lib/yes/core/process_managers/state.rb', line 58

def valid?
  required_attributes.all? { |attr| send(attr).present? }
end