Skip to content

Instantly share code, notes, and snippets.

@fmundaca
Created May 17, 2021 17:02
Show Gist options
  • Save fmundaca/b4a23e6fd2efa796d80ac189c27334f8 to your computer and use it in GitHub Desktop.
Save fmundaca/b4a23e6fd2efa796d80ac189c27334f8 to your computer and use it in GitHub Desktop.
module Concerns::Publishable
extend ActiveSupport::Concern
included do
if Rails.env.production?
after_commit :pubsub_create, on: :create
after_update :pubsub_update
after_destroy :pubsub_destroy
end
def pubsub_create
return if skip?
topics_config[:create].each do |topic|
::Pubsub::Messageable.new.perform(generate_topic(topic), self.class.to_s, build_message, ::Pubsub::Messageable::CREATE_EVENT)
end
rescue StandardError => e
SentryWorker.perform_async(e)
end
def pubsub_update
return if skip?
return if self.is_a?(Account) and not self.saved_change_to_active?
topics_config[:update].each do |topic|
::Pubsub::Messageable.new.perform(generate_topic(topic), self.class.to_s, build_message, ::Pubsub::Messageable::UPDATE_EVENT)
end
rescue StandardError => e
SentryWorker.perform_async(e)
end
def pubsub_destroy
return if skip?
topics_config[:destroy].each do |topic|
::Pubsub::Messageable.new.perform(generate_topic(topic), self.class.to_s, build_message, ::Pubsub::Messageable::DESTROY_EVENT)
end
rescue StandardError => e
SentryWorker.perform_async(e)
end
private
def generate_topic(topic)
ENV["PUBSUB_ENVIRONMENT"].downcase + "-" + topic.downcase
end
def skip?
return true if self.is_a?(User) && (self.account.nil? || self.enterprise.nil?)
return true if self.is_a?(Account) && self.enterprise.nil?
return false
# if self.is_a?(User) || self.is_a?(Account)
# self.enterprise.nil?
# else
# false
# end
end
def topics_config
{
create: [self.model_name.param_key + "s"],
update: [self.model_name.param_key + "s"],
destroy: [self.model_name.param_key + "s"]
}
end
def build_message
if self.is_a?(User)
self.as_json.merge!({
enterprise_id: self.enterprise&.id,
active: self.account&.active,
enterprise_token: self.enterprise.token,
internal_user: self.rankmi_internal?
}).to_json
elsif self.is_a?(Account)
self.as_json.merge!({enterprise_id: self.enterprise&.id, user_id: self.user.id}).to_json
elsif self.is_a?(EnterprisePositionFamily)
self.as_json.merge!({
competences: self.enterprise_competences.pluck(:token),
position_ids: self.enterprise_position_ids
}).to_json
else
self.to_json
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment