Sha256: 3de051c6144cc6f2e0c30f76a41286f7e2820dc93230aff21b23329790a58efe

Contents?: true

Size: 1.72 KB

Versions: 1

Compression:

Stored size: 1.72 KB

Contents

require 'active_support/concern'
require 'active_job_channel/channel'

module ActiveJobChannel
  module Broadcaster
    extend ActiveSupport::Concern

    class_methods do
      def active_job_channel(options = {})
        class_attribute :ajc_config
        self.ajc_config = { global_broadcast: false }
        ajc_config.merge!(options)

        after_perform :broadcast_success
        rescue_from '::StandardError' do |exception|
          broadcast_failure(exception)
          raise exception
        end
      end
    end

    # rubocop:disable Metrics/BlockLength
    included do
      private

      attr_writer :ajc_identifier

      def ajc_channel_name
        if ajc_config[:global_broadcast]
          if ajc_identifier.present?
            raise UnnecessaryIdentifierError, self.class.to_s
          end

          ::ActiveJobChannel::Channel::CHANNEL_NAME
        else
          [::ActiveJobChannel::Channel::CHANNEL_NAME, ajc_identifier].
            compact.
            join('#')
        end
      end

      def ajc_identifier
        if ajc_identifier_missing?
          raise ::ActiveJobChannel::NoIdentifierError, self.class.to_s
        end

        @ajc_identifier
      end

      def ajc_identifier_missing?
        !ajc_config[:global_broadcast] && @ajc_identifier.nil?
      end

      def broadcast_failure(exception)
        ::ActionCable.server.broadcast(
          ajc_channel_name,
          status: 'failure',
          data: serialize,
          error: exception.inspect
        )
      end

      def broadcast_success
        ::ActionCable.server.broadcast(
          ajc_channel_name,
          status: 'success',
          data: serialize
        )
      end
    end
    # rubocop:enable Metrics/BlockLength
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
active_job_channel-0.4.0 lib/active_job_channel/broadcaster.rb