Comparing identical DateTime objects in ruby — why are these two DateTime.now's not equal?

后端 未结 4 835
后悔当初
后悔当初 2021-01-13 12:55

In a rails app, I have model code of the form:

def do_stuff(resource)
  models = Model.where(resource: resource)
  operated_at = DateTime.now

  models.each         


        
4条回答
  •  伪装坚强ぢ
    2021-01-13 13:37

    You have three separate methods defined above with three separate operated_at local variables. Local variables are limited to the scope of the method which defines them.

    You need to define instance variables, which persist throughout a class. For example, you could:

    def Model
      attr_accessor :operated_at
    
      def do_stuff(resource)
        models = Model.where(resource: resource)
        operated_at = DateTime.now
    
        models.each { |model| some_operation(model, operated_at) }
    
        some_other_operation models, operated_at
      end
    
      def some_operation(model, operated_at)
        model.date_time_field = operated_at
        model.save
      end
    
      def some_other_operation(models, operated_at)
        models.each do |model|
          if model.date_time_field < operated_at
            # do something
          end    
        end
      end
    end  
    

    This would enable you to access operated_at throughout all of the class methods.

提交回复
热议问题