Module: Searchkick::Model

Defined in:
lib/searchkick/model.rb

Instance Method Summary collapse

Instance Method Details

#searchkick(options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/searchkick/model.rb', line 4

def searchkick(options = {})
  raise "Only call searchkick once per model" if respond_to?(:searchkick_index)

  class_eval do
    cattr_reader :searchkick_options, :searchkick_env, :searchkick_klass

    class_variable_set :@@searchkick_options, options.dup
    class_variable_set :@@searchkick_env, ENV["RACK_ENV"] || ENV["RAILS_ENV"] || "development"
    class_variable_set :@@searchkick_klass, self
    class_variable_set :@@searchkick_callbacks, options[:callbacks] != false
    class_variable_set :@@searchkick_index, options[:index_name] || [options[:index_prefix], model_name.plural, searchkick_env].compact.join("_")

    def self.searchkick_index
      index = class_variable_get :@@searchkick_index
      index = index.call if index.respond_to? :call
      Searchkick::Index.new(index)
    end

    extend Searchkick::Search
    extend Searchkick::Reindex
    include Searchkick::Similar

    if respond_to?(:after_commit)
      after_commit :reindex, if: proc{ self.class.search_callbacks? }
    else
      after_save :reindex, if: proc{ self.class.search_callbacks? }
      after_destroy :reindex, if: proc{ self.class.search_callbacks? }
    end

    def self.enable_search_callbacks
      class_variable_set :@@searchkick_callbacks, true
    end

    def self.disable_search_callbacks
      class_variable_set :@@searchkick_callbacks, false
    end

    def self.search_callbacks?
      class_variable_get(:@@searchkick_callbacks) && Searchkick.callbacks?
    end

    def should_index?
      true
    end

    def reindex
      index = self.class.searchkick_index
      if destroyed? or !should_index?
        begin
          index.remove self
        rescue Elasticsearch::Transport::Transport::Errors::NotFound
          # do nothing
        end
      else
        index.store self
      end
    end

    def search_data
      respond_to?(:to_hash) ? to_hash : serializable_hash
    end

  end
end