Skip to content

Instantly share code, notes, and snippets.

@lazaronixon
Created May 18, 2022 00:33
Show Gist options
  • Save lazaronixon/82b939179f2b1ee01b4111c8f471db83 to your computer and use it in GitHub Desktop.
Save lazaronixon/82b939179f2b1ee01b4111c8f471db83 to your computer and use it in GitHub Desktop.
Elastic search index async
module ElasticsearchExtension
module Callbacks
extend ActiveSupport::Concern
included do
after_commit -> { IndexJob.perform_later(:create, self.class.name, self.id) }, on: :create
after_commit -> { IndexJob.perform_later(:update, self.class.name, self.id) }, on: :update
after_commit -> { IndexJob.perform_later(:destroy, self.class.name, self.id) }, on: :destroy
end
end
end
class ElasticsearchExtension::IndexJob < ActiveJob::Base
discard_on ActiveRecord::RecordNotFound
discard_on Elasticsearch::Transport::Transport::Errors::NotFound
def perform(operation, record_class, record_id)
case operation
when :create
record = record_class.constantize.find(record_id)
record.__elasticsearch__.index_document
when :update
record = record_class.constantize.find(record_id)
record.__elasticsearch__.update_document
when :destroy
client = record_class.constantize.__elasticsearch__.client
index_name = record_class.constantize.__elasticsearch__.index_name
document_type = record_class.constantize.__elasticsearch__.document_type
client.delete index: index_name, type: document_type, id: record_id
else raise ArgumentError, "Unknown operation '#{operation}'"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment