Module: ElasticRecord::Callbacks

Defined in:
lib/elastic_record/callbacks.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/elastic_record/callbacks.rb', line 3

def self.included(base)
  return unless base.respond_to?(:after_save) &&  base.respond_to?(:after_destroy)

  base.class_eval do
    after_create do
      self.class.elastic_index.index_record self
    end

    after_update if: :changed? do
      method = self.class.elastic_index.partial_updates ? :update_record : :index_record
      self.class.elastic_index.send(method, self)
    end

    after_destroy do
      self.class.elastic_index.delete_document id
    end
  end
end

Instance Method Details

#as_partial_update_documentObject



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/elastic_record/callbacks.rb', line 38

def as_partial_update_document
  json = {}

  mappings = elastic_index.mapping[:properties]
  changed.each do |field|
    if field_mapping = mappings[field]
      json[field] = elastic_search_value field, field_mapping
    end
  end

  amend_partial_update_document(json) if respond_to?(:partial_update_document)

  json
end

#as_searchObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/elastic_record/callbacks.rb', line 22

def as_search
  json = {}

  elastic_index.mapping[:properties].each do |field, mapping|
    value = elastic_search_value field, mapping

    unless value.nil?
      json[field] = value
    end
  end

  amend_as_search(json) if respond_to?(:amend_as_search)

  json
end

#elastic_search_value(field, mapping) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/elastic_record/callbacks.rb', line 53

def elastic_search_value(field, mapping)
  value = try field
  return if value.nil?

  value = case mapping[:type]
    when :object
      value.as_search
    when :nested
      value.map(&:as_search)
    else
      value
    end

  if value.present? || value == false
    value
  end

rescue
  raise "Field not found for #{field.inspect}"
end