Module: Marples::ModelActionBroadcast

Defined in:
lib/marples/model_action_broadcast.rb

Constant Summary collapse

TRANSACTION_ACTIONS =
:create, :update, :destroy
CALLBACKS =
TRANSACTION_ACTIONS + [:save, :commit]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/marples/model_action_broadcast.rb', line 10

def self.included base
  base.class_eval do
    # Something that response to #subscribe and #publish - although we
    # only use #publish in this mixin.
    class_attribute :marples_transport
    # You *will* need to set this yourself in each application.
    class_attribute :marples_client_name
    # If you'd like the actions performed by Marples to be logged, set a
    # logger. By default this uses the NullLogger.
    class_attribute :marples_logger
    self.marples_logger = NullLogger.instance

    CALLBACKS.each do |callback|
      callback_action = callback.to_s =~ /e$/ ? "#{callback}d" : "#{callback}ed"
      after_callback = "after_#{callback}"
      next unless respond_to? after_callback

      notify = lambda { |record| record.broadcast_action(callback_action) }
      if TRANSACTION_ACTIONS.include?(callback) && respond_to?(:after_commit)
        after_commit :on => callback, &notify
      else
        send after_callback, &notify
      end
    end

    def self.marples_client
      @marples_client ||= build_marples_client
    end

    def self.build_marples_client
      Marples::Client.new transport: marples_transport,
        client_name: marples_client_name, logger: marples_logger
    end
  end
end

Instance Method Details

#broadcast_action(callback_action) ⇒ Object



6
7
8
# File 'lib/marples/model_action_broadcast.rb', line 6

def broadcast_action(callback_action)
  self.class.marples_client.send callback_action, self
end