Sha256: 33ecebe45cbf478c4fcfe9aa734f436db5eb0c77bf612fa823a6db2bf8713c2b

Contents?: true

Size: 1.87 KB

Versions: 5

Compression:

Stored size: 1.87 KB

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|
      event = data.merge(
          actor: ( data[:actor] ? send(data[:actor]) : self ),
          target: ( data[:target] ? self : nil),
          at: ( data[:at] ? send(data[:at]) : nil)
      ).except(:watch, :if)
      need_to_fire = case (ifarg = data[:if])
                       when Proc
                         instance_exec &ifarg
                       when Symbol
                         send(ifarg)
                       else
                         true
                     end
      Reactor::Event.delay.publish name, event if need_to_fire
    end
  end

  def reschedule_events
    self.class.events.each do |name, data|
      attr_changed_method = "#{data[:watch] || data[:at]}_changed?"
      if data[:at] && respond_to?(attr_changed_method) && send(attr_changed_method)
        Reactor::Event.delay.reschedule name,
          at: send(data[:at]),
          actor: ( data[:actor] ? send(data[:actor]) : self ),
          target: ( data[:target] ? self : nil),
          was: send("#{data[:at]}_was")
      end
      if data[:if]
        need_to_fire = case (ifarg = data[:if])
                         when Proc
                           instance_exec &ifarg
                         when Symbol
                           send(ifarg)
                       end
        Reactor::Event.delay.publish name, actor: self if need_to_fire
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
reactor-0.2.10 lib/reactor/models/concerns/eventable.rb
reactor-0.2.9 lib/reactor/models/concerns/eventable.rb
reactor-0.2.8 lib/reactor/models/concerns/eventable.rb
reactor-0.2.7 lib/reactor/models/concerns/eventable.rb
reactor-0.2.6 lib/reactor/models/concerns/eventable.rb