Class: EventSourcing::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/event_sourcing/command.rb,
lib/event_sourcing/command/bus.rb

Defined Under Namespace

Classes: Bus

Class Method Summary collapse

Class Method Details

.define(*fields, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/event_sourcing/command.rb', line 5

def self.define(*fields, &block)
  raise "Commands require an execution block" unless block_given?

  Class.new(self) do
    public_class_method :new
    attr_reader(*fields)

    define_method :initialize do |properties = {}|
      missing_keys = fields - properties.keys
      
      if missing_keys.any?
        raise ArgumentError, "missing keyword: #{missing_keys.first}"
      end

      fields.each do |field|
        instance_variable_set("@#{field}", properties[field])
      end
    end

    define_method :execute do |*args|
      instance_exec(*args, &block)
    end
  end
end