Sha256: b3004614ff2c024cc56c36b16a3cd2248b69e4d229913ced493b53d790b54ff7

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

module PubSubModelSync
  class Subscriber
    attr_accessor :klass, :action, :attrs, :settings

    # @param settings: (Hash) { id: :id, direct_mode: false,
    #                           from_klass: klass, from_action: action }
    def initialize(klass, action, attrs: nil, settings: {})
      def_settings = { id: :id, direct_mode: false,
                       from_klass: klass, from_action: action }
      @klass = klass
      @action = action
      @attrs = attrs
      @settings = def_settings.merge(settings)
    end

    def eval_message(message)
      if settings[:direct_mode]
        run_class_message(message)
      else
        run_model_message(message)
      end
    end

    private

    def run_class_message(message)
      model_class = klass.constantize
      model_class.send(action, message)
    end

    # support for: create, update, destroy
    def run_model_message(message)
      model = find_model(message)
      if action == :destroy
        model.destroy!
      else
        populate_model(model, message)
        return if action == :update && !model.ps_subscriber_changed?(message)

        model.save!
      end
    end

    def find_model(message)
      model_class = klass.constantize
      return model_class.ps_find_model(message) if model_class.respond_to?(:ps_find_model)

      model_class.where(model_identifiers(message)).first_or_initialize
    end

    def model_identifiers(message)
      identifiers = Array(settings[:id])
      identifiers.map { |key| [key, message[key.to_sym]] }.to_h
    end

    def populate_model(model, message)
      values = message.slice(*attrs)
      values.each do |attr, value|
        model.send("#{attr}=", value)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pub_sub_model_sync-0.5.0.1 lib/pub_sub_model_sync/subscriber.rb
pub_sub_model_sync-0.5.0 lib/pub_sub_model_sync/subscriber.rb