Sha256: d73e98400e6119295fd59efc8a0ba29465d5f3a316a7f60e21d8d65e418677ed

Contents?: true

Size: 1010 Bytes

Versions: 11

Compression:

Stored size: 1010 Bytes

Contents

# frozen_string_literal: true

module PubSubModelSync
  class Publisher
    attr_accessor :attrs, :actions, :klass, :as_klass

    def initialize(attrs, klass, actions = nil, as_klass = nil)
      @attrs = attrs
      @klass = klass
      @actions = actions || %i[create update destroy]
      @as_klass = as_klass || klass
    end

    def payload(model, action)
      PubSubModelSync::Payload.new(payload_data(model), payload_attrs(model, action))
    end

    private

    def payload_data(model)
      source_props = @attrs.map { |prop| prop.to_s.split(':').first }
      data = model.as_json(only: source_props, methods: source_props)
      aliased_props = @attrs.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 payload_attrs(model, action)
      { klass: (as_klass || model.class.name).to_s, action: action.to_sym }
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
pub_sub_model_sync-0.5.8.2 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.8.1 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.8 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.7.1 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.7 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.6 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.5 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.4.1 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.4 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.3 lib/pub_sub_model_sync/publisher.rb
pub_sub_model_sync-0.5.2 lib/pub_sub_model_sync/publisher.rb