views:

20

answers:

2

Hey there,

I'm currently fighting with the rails class_caching mechanism as I need to return a file path that changes discrete over time. It is used to constantly change a log file path after the amount of GRAIN seconds and returns a fully working timestamp:

GRAIN = 30

def self.file_path  
   timestamp = (Time.now.to_i / GRAIN) * GRAIN
   return FILE_DIR + "tracking_#{timestamp.call}.csv"  
end

This works really great if the class_caching of rails is set to false. But of course the app is to run with enabled class caching. And as soon as I enable it, either the timestamp variable is cached or the Time.now expression.

I tried to solve this with a proc block, but no success:

def self.file_path
    timestamp = Proc.new { (Time.now.to_i / GRAIN) * GRAIN }
    return FILE_DIR + "tracking_#{timestamp.call}.csv"
end

Is there anything like a cache disabled scope I could use or something like skip_class_caching :file_path? Or any other solutions?

Thank you for your help!

A: 

It's not entirely clear where your code is located, but ActiveRecord has an uncached method that suspends the cache for whatever is inside its block.

jdl
A: 

I found the problem. Not the Time.now was beeing cached but a logger instance. It was assigned in another method calling the file_path.

As long as the class caching was disabled the environment forgot about the class variable between the requests. But as soon as it was enabled the class variable stayed the same - and desired value - but never changed.

So I had to add a simple condition that checks if the file_path changed since the last request. If so, the class variable is reassigned, otherwise it keeps the same desired value.

I changed from:

def self.tracker
    file_path = Tracking.file_path
    @@my_tracker ||= Logger.new(file_path)
end

to:

def self.tracker
    file_path = Tracking.file_path
    @@my_tracker = Logger.new(file_path) if @@my_tracker.nil? or Tracking.shift_log?(file_path)
    @@my_tracker
end

Thank you for your help anyways!

Thomas Fankhauser