lib/mongoid/touchable.rb in mongoid-7.0.13 vs lib/mongoid/touchable.rb in mongoid-7.1.0.rc0

- old
+ new

@@ -1,23 +1,24 @@ # frozen_string_literal: true # encoding: utf-8 + module Mongoid module Touchable module InstanceMethods # Touch the document, in effect updating its updated_at timestamp and # optionally the provided field to the current time. If any belongs_to - # relations exist with a touch option, they will be updated as well. + # associations exist with a touch option, they will be updated as well. # # @example Update the updated_at timestamp. # document.touch # # @example Update the updated_at and provided timestamps. # document.touch(:audited) # - # @note This will not autobuild relations if those options are set. + # @note This will not autobuild associations if those options are set. # # @param [ Symbol ] field The name of an additional field to update. # # @return [ true/false ] false if record is new_record otherwise true. # @@ -39,11 +40,11 @@ end end extend self - # Add the association to the touchable relations if the touch option was + # Add the association to the touchable associations if the touch option was # provided. # # @example Add the touchable. # Model.define_touchable!(assoc) # @@ -63,19 +64,19 @@ end private # Define the method that will get called for touching belongs_to - # relations. + # associations. # # @api private # - # @example Define the touch relation. + # @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 relation. + # @param [ Symbol ] name The name of the association. # @param [ Association ] association The association metadata. # # @since 3.1.0 # # @return [ Symbol ] The method name. @@ -86,17 +87,24 @@ [ association.relation_class ] end relation_classes.each { |c| c.send(:include, InstanceMethods) } method_name = "touch_#{name}_after_create_or_destroy" - association.inverse_class.class_eval <<-TOUCH, __FILE__, __LINE__ + 1 - def #{method_name} - without_autobuild do - relation = __send__(:#{name}) - relation.touch #{":#{association.touch_field}" if association.touch_field} if relation + association.inverse_class.class_eval do + define_method(method_name) do + without_autobuild do + if relation = __send__(name) + if association.touch_field + # Note that this looks up touch_field at runtime, rather than + # at method definition time. + relation.touch association.touch_field + else + relation.touch + end end end - TOUCH + end + end method_name.to_sym end end end