Method: Elasticsearch::Model::Indexing::InstanceMethods.included

Defined in:
lib/elasticsearch/model/indexing.rb

.included(base) ⇒ Object


322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/elasticsearch/model/indexing.rb', line 322

def self.included(base)
  # Register callback for storing changed attributes for models
  # which implement `before_save` and return changed attributes
  # (ie. when `Elasticsearch::Model` is included)
  #
  # @note This is typically triggered only when the module would be
  #       included in the model directly, not within the proxy.
  #
  # @see #update_document
  #
  base.before_save do |obj|
    if obj.respond_to?(:changes_to_save) # Rails 5.1
      changes_to_save = obj.changes_to_save
    elsif obj.respond_to?(:changes)
      changes_to_save = obj.changes
    end

    if changes_to_save
      attrs = obj.instance_variable_get(:@__changed_model_attributes) || {}
      latest_changes = changes_to_save.inject({}) { |latest_changes, (k,v)| latest_changes.merge!(k => v.last) }
      obj.instance_variable_set(:@__changed_model_attributes, attrs.merge(latest_changes))
    end
  end if base.respond_to?(:before_save)
end