Module: Mongoid::Association::Referenced::AutoSave

Extended by:
ActiveSupport::Concern
Included in:
Mongoid::Association
Defined in:
build/mongoid-master/lib/mongoid/association/referenced/auto_save.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_autosave!(association) ⇒ Class

Define the autosave method on an association's owning class for an associated object.

Examples:

Define the autosave method:

Association::Referenced::Autosave.define_autosave!(association)

Parameters:

  • association (Association)

    The association for which autosaving is enabled.

Returns:

  • (Class)

    The association's owner class.

Since:

  • 7.0



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'build/mongoid-master/lib/mongoid/association/referenced/auto_save.rb', line 58

def self.define_autosave!(association)
  association.inverse_class.tap do |klass|
    save_method = :"autosave_documents_for_#{association.name}"
    klass.send(:define_method, save_method) do
      if before_callback_halted?
        self.before_callback_halted = false
      else
        __autosaving__ do
          if assoc_value = ivar(association.name)
            Array(assoc_value).each do |doc|
              doc.with(persistence_context) do |d|
                d.save
              end
            end
          end
        end
      end
    end
    klass.after_save save_method, unless: :autosaved?
  end
end

Instance Method Details

#__autosaving__Object

Begin the associated autosave.

Examples:

Begin autosave.

document.__autosaving__

Since:

  • 3.1.3



29
30
31
32
33
34
# File 'build/mongoid-master/lib/mongoid/association/referenced/auto_save.rb', line 29

def __autosaving__
  Threaded.begin_autosave(self)
  yield
ensure
  Threaded.exit_autosave(self)
end

#autosaved?true, false

Used to prevent infinite loops in associated autosaves.

Examples:

Is the document autosaved?

document.autosaved?

Returns:

  • (true, false)

    Has the document already been autosaved?

Since:

  • 3.0.0



19
20
21
# File 'build/mongoid-master/lib/mongoid/association/referenced/auto_save.rb', line 19

def autosaved?
  Threaded.autosaved?(self)
end

#changed_for_autosave?(doc) ⇒ Boolean

Check if there is changes for auto-saving

document.changed_for_autosave?

Examples:

Return true if there is changes on self or in

autosaved associations.

Returns:

Since:

  • 3.1.3



43
44
45
# File 'build/mongoid-master/lib/mongoid/association/referenced/auto_save.rb', line 43

def changed_for_autosave?(doc)
  doc.new_record? || doc.changed? || doc.marked_for_destruction?
end