Sha256: 1d5c4bdf9960daa482a8b91a84863f311ff9a0b9dc80ab3ef9eafc7400eb39b4

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

require 'active_support/concern'
require 'roo_on_rails/routemaster/publishers'

module RooOnRails
  module Routemaster
    module LifecycleEvents
      extend ActiveSupport::Concern

      ACTIVE_RECORD_TO_ROUTEMASTER_EVENT_MAP = {
        create: :created,
        update: :updated,
        destroy: :deleted,
        noop: :noop
      }.freeze
      private_constant :ACTIVE_RECORD_TO_ROUTEMASTER_EVENT_MAP

      def publish_lifecycle_event(event)
        publish_event(event, force_publish: false)
      end

      def publish_lifecycle_event!(event)
        publish_event(event, force_publish: true)
      end

      private

      def publish_event(event, force_publish:)
        publishers = Routemaster::Publishers.for(self, routemaster_event_type(event))
        publishers.each do |publisher|
          begin
            publisher.publish!(force_publish: force_publish)
          rescue => e
            Raven.report_exception(e) if defined?(Raven)
          end
        end
      end

      def routemaster_event_type(event)
        ACTIVE_RECORD_TO_ROUTEMASTER_EVENT_MAP[event].tap do |type|
          raise "invalid lifecycle event '#{event}'" unless type
        end
      end

      %i(create update destroy noop).each do |event|
        define_method("publish_lifecycle_event_on_#{event}") do
          publish_lifecycle_event(event)
        end
      end

      module ClassMethods
        def publish_lifecycle_events(*events)
          events = events.any? ? events : %i(create update destroy)
          events.each do |event|
            after_commit(
              :"publish_lifecycle_event_on_#{event}",
              on: event
            )
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
roo_on_rails-2.0.0.pre.pre.1 lib/roo_on_rails/routemaster/lifecycle_events.rb