Class: FourthDimensional::Command

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/fourth_dimensional/command.rb

Overview

FourthDimensional::Command

Commands are the input to create events. They provide an early validation step to ensuring the data format is correct before validating the current state of the system.

class AddPost < FourthDimensional::Command
  attributes :title, :body, :published
  validates_presence_of :title, :body
end

AddPost.new # => raises ArgumentError.new("missing keywords: aggregate_id, :title, :body, :published)
command = AddPost.new(aggregate_id: '1-2-3', title: 'post-title', body: 'post-body', published: false)
command.valid? # => true
command.aggregate_id # => '1-2-3'
command.title # => 'post-title'
command.body # => 'post-body'
command.published # => false

command.to_h # => {'title' => 'post-title', 'body' => 'post-body', 'published' => false}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(aggregate_id:) ⇒ Command

Returns a new instance of Command.



30
31
32
# File 'lib/fourth_dimensional/command.rb', line 30

def initialize(aggregate_id:)
  @aggregate_id = aggregate_id
end

Instance Attribute Details

#aggregate_idObject (readonly)

The aggregate the command is acting on



28
29
30
# File 'lib/fourth_dimensional/command.rb', line 28

def aggregate_id
  @aggregate_id
end

Class Method Details

.attributes(*attributes) ⇒ Object

Defines an initializer with required keyword arguments, readonly only attributes and to_h to access all defined attributes

class AddPost < FourthDimensional::Command
  attributes :title, :body, :published
end


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/fourth_dimensional/command.rb', line 44

def self.attributes(*attributes)
  attr_reader *attributes

  method_arguments = attributes.map { |arg| "#{arg}:" }.join(', ')
  method_assignments = attributes.map { |arg| "@#{arg} = #{arg}" }.join(';')
  method_attrs_to_hash = attributes.map { |arg| "'#{arg}' => #{arg}" }.join(',')

  class_eval <<~CODE
    def initialize(aggregate_id:, #{method_arguments})
      @aggregate_id = aggregate_id
      #{method_assignments}
    end

    def to_h
      {#{method_attrs_to_hash}}
    end
  CODE
end

Instance Method Details

#to_hObject



34
35
36
# File 'lib/fourth_dimensional/command.rb', line 34

def to_h
  {}
end