Sha256: fe9dcb6544823ce4a4660afe903e14da9836507f72589a6172ae642b88eb3919

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

require 'elasticsearch/model'
require 'custom_attributes/fluent_search_query'

module CustomAttributes
  module Searchable
    extend ActiveSupport::Concern

    included do
      include Elasticsearch::Model

      index_name "#{name.downcase.pluralize}-#{Rails.env}"

      # For ActiveRecord-based models, use the after_commit callback to
      # protect your data against inconsistencies caused by transaction rollbacks
      if any? { |obj| obj.is_a?(ActiveRecord::Base) }
        after_commit on: [:create] do
          index_document_or_fail
        end

        after_commit on: [:update] do
          index_document_or_fail
        end

        after_commit on: [:destroy] do
          delete_document_or_fail
        end
      else
        # everything else can use the standard implementation
        include Elasticsearch::Model::Callbacks
      end

      # helper function to initialize index
      def self.set_up_search
        __elasticsearch__.create_index!
        __elasticsearch__.refresh_index!
        import
      end

      # entrypoint for the fluent query builder
      def self.searchable
        CustomAttributes::FluentSearchQuery.new new
      end

      # default connection error handling, override in model!
      def self.handle_search_connection_error(exception)
        raise exception
      end

      private

      def index_document_or_fail
        __elasticsearch__.index_document
      rescue Faraday::ConnectionFailed => e
        handle_search_connection_error(e)
      end

      def delete_document_or_fail
        __elasticsearch__.delete_document
      rescue Faraday::ConnectionFailed => e
        handle_search_connection_error(e)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
create_custom_attributes-0.5.0 lib/custom_attributes/concerns/searchable.rb