Sha256: 5eff8fdee4bd232d3283f7bb0b99449d6585c87149cced5248c046f248233535

Contents?: true

Size: 1.28 KB

Versions: 1

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

module ExternalServices
  class Service < ::ActiveRecord::Base
    self.table_name = :external_services

    belongs_to :subject, polymorphic: true
    serialize :extra_data, coder: JSON

    after_update :on_first_sync, if: proc { # Rails 5.1+ support
      (respond_to?(:saved_change_to_external_id?) ? saved_change_to_external_id? : external_id_changed?) &&
        (respond_to?(:external_id_before_last_save) ? external_id_before_last_save : external_id_was).nil?
    }

    def self.to_sym
      to_s.demodulize.underscore.to_sym
    end

    def on_subject_create(subj)
      method = subj.send("#{api_name}_id").present? ? :put : :post
      subj.send("#{api_name}_api_action", method)
    end

    def on_subject_update(subj)
      method = subj.send("#{api_name}_id").present? ? :put : :post
      return true if (subj.respond_to?(:became_archived?) && subj.became_archived?) && method == :post

      subj.send("#{api_name}_api_action", method)
    end

    def on_subject_destroy(subj)
      subj.send("#{api_name}_api_action", :delete)
    end

    def api_name
      self.class.to_sym
    end

    protected

    def on_first_sync
      callback_name = "on_#{api_name}_first_sync"
      subject.send(callback_name) if subject.respond_to?(callback_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
external_services-0.5.4 app/models/external_services/service.rb