module Mongoid::Touchable
Mixin module which is included in Mongoid::Document
to add “touch” functionality to update a document’s timestamp(s) atomically.
Constants
- SUPPRESS_TOUCH_CALLBACKS_KEY
The key to use to store the active touch callback suppression statuses
Public Instance Methods
Add the association to the touchable associations if the touch option was provided.
@example Add the touchable.
Model.define_touchable!(assoc)
@param [ Mongoid::Association::Relatable
] association The association metadata.
@return [ Class ] The model class.
# File lib/mongoid/touchable.rb, line 153 def define_touchable!(association) name = association.name method_name = define_relation_touch_method(name, association) association.inverse_class.tap do |klass| klass.after_save method_name klass.after_destroy method_name # Embedded docs handle touch updates recursively within # the #touch method itself klass.after_touch method_name unless association.embedded? end end
Suppresses touch callbacks for the named class, for the duration of the associated block.
@api private
# File lib/mongoid/touchable.rb, line 170 def suppress_touch_callbacks(name) save, touch_callback_statuses[name] = touch_callback_statuses[name], true yield ensure touch_callback_statuses[name] = save end
Queries whether touch callbacks are being suppressed for the named class.
@return [ true | false ] Whether touch callbacks are suppressed.
@api private
# File lib/mongoid/touchable.rb, line 183 def touch_callbacks_suppressed?(name) touch_callback_statuses[name] end
Private Instance Methods
Define the method that will get called for touching belongs_to associations.
@api private
@example Define the touch association.
Model.define_relation_touch_method(:band) Model.define_relation_touch_method(:band, :band_updated_at)
@param [ Symbol ] name The name of the association. @param [ Mongoid::Association::Relatable
] association The association metadata.
@return [ Symbol ] The method name.
# File lib/mongoid/touchable.rb, line 214 def define_relation_touch_method(name, association) method_name = "touch_#{name}_after_create_or_destroy" association.inverse_class.class_eval do define_method(method_name) do without_autobuild do if !touch_callbacks_suppressed? && relation = __send__(name) # This looks up touch_field at runtime, rather than at method definition time. # If touch_field is nil, it will only touch the default field (updated_at). relation.touch(association.touch_field) end end end end method_name.to_sym end
Returns a hash to be used to store and query the various touch callback suppression statuses for different classes.
@return [ Hash ] The hash that contains touch callback suppression
statuses
# File lib/mongoid/touchable.rb, line 197 def touch_callback_statuses Threaded.get(SUPPRESS_TOUCH_CALLBACKS_KEY) { {} } end