Sha256: 8f3a6f899d5e8084ef39c5d2cf1374b17f7f3d101844c170babedc1c2f36a9db

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module PubSubModelSync
  module PublisherConcern
    def self.included(base)
      base.extend(ClassMethods)
    end

    # Permit to skip a publish callback
    def ps_msync_skip_for?(_action)
      false
    end

    module ClassMethods
      # Permit to publish crud actions (:create, :update, :destroy)
      # @param settings (Hash): { actions: nil, as_klass: nil, id: nil }
      def ps_msync_publish(attrs, settings = {})
        actions = settings.delete(:actions) || %i[create update destroy]
        @ps_msync_publisher_settings = settings.merge(attrs: attrs)
        ps_msync_register_callbacks(actions)
      end

      def ps_msync_publisher_settings
        @ps_msync_publisher_settings
      end

      def ps_msync_class_publish(data, action:, as_klass: nil)
        as_klass = (as_klass || name).to_s
        ps_msync_publisher.publish_data(as_klass, data, action.to_sym)
      end

      def ps_msync_publisher
        PubSubModelSync::Publisher.new
      end

      private

      def ps_msync_register_callbacks(actions)
        actions.each do |action|
          after_commit(on: action) do |model|
            unless model.ps_msync_skip_for?(action)
              publisher = model.class.ps_msync_publisher
              publisher.publish_model(model, action.to_sym)
            end
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
pub_sub_model_sync-0.1.2 lib/pub_sub_model_sync/publisher_concern.rb
pub_sub_model_sync-0.1.1 lib/pub_sub_model_sync/publisher_concern.rb
pub_sub_model_sync-0.1.0 lib/pub_sub_model_sync/publisher_concern.rb