Sha256: 78075fc035f781645c00281d6d5f67b8675d91096997fe50b43af3d60f9cc1f6

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module PubSubModelSync
  class Publisher
    attr_accessor :connector
    delegate :publish, to: :connector

    def initialize
      @connector = PubSubModelSync::Connector.new
    end

    def publish_data(klass, data, action)
      attributes = self.class.build_attrs(klass, action)
      publish(data, attributes)
    end

    # @param settings (Hash): { attrs: [], as_klass: nil, id: nil }
    def publish_model(model, action, settings = nil)
      return if model.ps_skip_sync?(action)

      settings ||= model.class.ps_publisher_info(action)
      attributes = build_model_attrs(model, action, settings)
      data = {}
      data = build_model_data(model, settings[:attrs]) if action != :destroy
      res_before = model.ps_before_sync(action, data)
      return if res_before == :cancel

      publish(data.symbolize_keys, attributes)
      model.ps_after_sync(action, data)
    end

    def self.build_attrs(klass, action, id = nil)
      {
        klass: klass.to_s,
        action: action.to_sym,
        id: id
      }
    end

    private

    def build_model_data(model, model_props)
      source_props = model_props.map { |prop| prop.to_s.split(':').first }
      data = model.as_json(only: source_props, methods: source_props)
      aliased_props = model_props.select { |prop| prop.to_s.include?(':') }
      aliased_props.each do |prop|
        source, target = prop.to_s.split(':')
        data[target] = data.delete(source)
      end
      data.symbolize_keys
    end

    def build_model_attrs(model, action, settings)
      as_klass = (settings[:as_klass] || model.class.name).to_s
      id_val = model.send(settings[:id] || :id)
      self.class.build_attrs(as_klass, action, id_val)
    end

    def log(msg)
      PubSubModelSync::Config.log(msg)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pub_sub_model_sync-0.2.4 lib/pub_sub_model_sync/publisher.rb