Sha256: 965da0146e6beb3e5251c2ba53c00f8974c0f2f5e1dbdebf425c52ca4d0955dd

Contents?: true

Size: 1001 Bytes

Versions: 1

Compression:

Stored size: 1001 Bytes

Contents

module Reactor::Eventable
  extend ActiveSupport::Concern

  included do
    after_commit :schedule_events, if: :persisted?, on: :create
    after_commit :reschedule_events, if: :persisted?, on: :update
  end

  def publish(name, data = {})
    Reactor::Event.publish(name, data.merge(actor: self) )
  end

  module ClassMethods
    def publishes(name, data = {})
      events[name] = data
    end

    def events
      @events ||= {}
    end
  end

  private

  def schedule_events
    self.class.events.each do |name, data|
      data = data.merge(
          at: ( data[:at] ? send(data[:at]) : nil), actor: self
      ).except(:watch)
      Reactor::Event.delay.publish name, data
    end
  end

  def reschedule_events
    self.class.events.each do |name, data|
      if data[:at] && send("#{data[:watch] || data[:at]}_changed?")
        Reactor::Event.delay.reschedule name,
          at: send(data[:at]),
          actor: self,
          was: send("#{data[:at]}_was")
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
reactor-0.1.1 lib/reactor/models/concerns/eventable.rb