Skip to content

Instantly share code, notes, and snippets.

@dimroc
Last active August 29, 2015 14:10
Show Gist options
  • Select an option

  • Save dimroc/9607b9bdecdb9bb55cce to your computer and use it in GitHub Desktop.

Select an option

Save dimroc/9607b9bdecdb9bb55cce to your computer and use it in GitHub Desktop.
module BackgroundIndexer
extend ActiveSupport::Concern
included do
after_save { IndexerJob.perform_later('index', self.class.index_name, self.class.name.downcase, self) }
after_destroy { IndexerJob.perform_later('delete', self.class.index_name, self.class.name.downcase, self.id) }
end
end
class IndexerJob < ActiveJob::Base
Logger = Sidekiq.logger.level == Logger::DEBUG ? Sidekiq.logger : nil
Client = Elasticsearch::Client.new logger: Logger
def perform(operation, index_name, type, record)
case operation.to_s
when 'index'
Client.index(index: index_name,
type: type,
id: record.id,
body: record.__elasticsearch__.as_indexed_json)
when 'delete'
Client.delete(index: index_name, type: type, id: record)
else raise ArgumentError, "Unknown operation '#{operation}'"
end
end
end
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include BackgroundIndexer
index_name "#{Rails.env}-#{self.name.downcase.pluralize}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment