Sha256: 00aaa51ab21ac44bf755e7b37f501afa13f8f34f2d750df14b4166282e223640

Contents?: true

Size: 1.08 KB

Versions: 1

Compression:

Stored size: 1.08 KB

Contents

module Eventus
  module AggregateRoot
    module ClassMethods
      def find(id)
        instance = self.new
        stream = Eventus::Stream.new(id, persistence, Eventus.dispatcher)
        instance.populate(stream)
        instance
      end

      def apply(event_name, &block)
        raise "A block is required" unless block_given?
        define_method("apply_#{event_name}", &block)
      end

      def persistence
        @persistence ||= Eventus.persistence
      end
    end

    module InstanceMethods
      def populate(stream)
        @stream = stream
        stream.committed_events.each do |event|
          apply_change event[:name], event[:body], false
        end
      end

      def save
        @stream.commit
      end

      protected

      def apply_change(name, body=nil, is_new=true)
        method_name = "apply_#{name}"
        self.send method_name, body if self.respond_to?(method_name)

        @stream.add(name, body) if is_new
      end
    end

    def self.included(base)
      base.send :include, InstanceMethods
      base.send :extend, ClassMethods
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eventus-0.3.0 lib/eventus/aggregate_root.rb