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
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.