Module: EventSource::Entity::ClassMethods

Defined in:
lib/event_source/entity.rb

Instance Method Summary collapse

Instance Method Details

#create(uid = EventSource::UIDGenerator.generate_id) {|entity| ... } ⇒ Object

Yields:

  • (entity)


4
5
6
7
8
9
10
# File 'lib/event_source/entity.rb', line 4

def create(uid = EventSource::UIDGenerator.generate_id)
    entity = self.new
    entity.send(:uid=, uid)

    yield entity if block_given?
    entity
end

#on_event(name, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/event_source/entity.rb', line 28

def on_event(name, &block)
    self.send(:define_method, name) do |*args|
        returnValue = block.call(args.unshift(self))
        entity_events << EventSource::Event.create(name, self)

        # if repo is nil, that's because this isn't being executed in the context of a
        # transaction and the result won't be saved
        repo = EventSource::EntityRepository.current
        repo.entities << self if repo

        returnValue
    end
end

#rebuild(uid, events) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/event_source/entity.rb', line 12

def rebuild(uid, events)
    return self.create(uid) if events.length == 0

    entity = self.new
    entity.send(:uid=, uid)

    events.each do |e|
        data = JSON.parse(e.data)
        data.keys.each do |attr|
            entity.send("#{attr}=", data[attr])
        end
    end

    entity
end