Sha256: fb5678d4a1be3d763a854313bca01f6e694c6fe53ffb8cefcc82d566dd2c6a0a

Contents?: true

Size: 1.45 KB

Versions: 10

Compression:

Stored size: 1.45 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 persistence
        @persistence ||= Eventus.persistence
      end

      def conflicts(added = {})
        @event_conflicts ||= {}
        added.each do |k,v|
          @event_conflicts[k.to_s] = v.respond_to?(:map) ? v.map{|e| e.to_s} : [v.to_s]
        end
      end

      def conflict?(e1, e2)
        return false unless @event_conflicts
        s1 = e1.to_s
        s2 = e2.to_s
        @event_conflicts.fetch(s1,[]).include?(s2) || @event_conflicts.fetch(s2,[]).include?(s1)
      end
    end

    module InstanceMethods

      def save
        version = @stream.version
        @stream.commit
        true
      rescue Eventus::ConcurrencyError => e
        on_concurrency_error(version, e)
      end

      protected

      def on_concurrency_error(version, e)
        committed = @stream.committed_events.drop(version)
        uncommitted = @stream.uncommitted_events
        conflict = committed.any?{ |c| uncommitted.any? {|u| self.class.conflict?(c['name'], u['name'])} }
        raise Eventus::ConflictError if conflict
        false
      end

    end

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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
eventus-0.6.7 lib/eventus/aggregate_root.rb
eventus-0.6.6 lib/eventus/aggregate_root.rb
eventus-0.6.5 lib/eventus/aggregate_root.rb
eventus-0.6.4 lib/eventus/aggregate_root.rb
eventus-0.6.3 lib/eventus/aggregate_root.rb
eventus-0.6.2 lib/eventus/aggregate_root.rb
eventus-0.6.1 lib/eventus/aggregate_root.rb
eventus-0.6.0 lib/eventus/aggregate_root.rb
eventus-0.5.1 lib/eventus/aggregate_root.rb
eventus-0.5.0 lib/eventus/aggregate_root.rb