views:

45

answers:

2

I have an app that heavily relies on dates. There is a moderately expensive calculation that is needed to set these dates, based on the current date. As far as each request is concerned, these dates are constants -- they don't change once created -- but they do change throughout the week. The dates are used in both controllers and models.

My problem is this:

  • if the dates didn't change each day, I could set them in config/initializers. But initializers are only evaluated when the server restarts
  • if i set the dates in applicationController using before_filter, the dates aren't available to my models

Any ideas? Am I looking at this all wrong? Thanks.

+2  A: 

One way is: make a singleton class which, when asked for an instance, checks the date. Off top of my head,

class MyDates
  def self.get_instance
    unless @instance && @date == Date.new
      @date = Date.new
      @instance = self.new(@date)
    end
    @instance
  end

  def initialize(date)
    # calculate the expensive stuff
  end
end
Amadan
+1  A: 

I think that here you can use Rails caching. Look here and here for more details and examples.

Basicaly, you can write to cache:

Rails.cache.write('date', Date.today)

and read:

Rails.cache.read('date')

You can use it in whole Rails application (models, views, controllers, ...).

You can store any object in cache. Default caching uses memory and is availble for single Rails instance, however you can use different cache storing method.

klew
This is on the right track. You'll need to set your date as part of the cache-key in order to have it automatically cache-miss when the date changes. Something like: https://gist.github.com/6c381274d6ad7a78b0d0 -In this case, the fetch will return "some_cache_key_#{Date.today}" if it exists. If it doesn't exist yet, then it will call my_expensive_operation and then save the results of that method into the cache under "some_cache_key_#{Date.today}"
semanticart
I ended up using a combination of klew's and Amadan's answers... so that now I only need to generate the dates once per day. Thanks so much everybody, this was a huge help.
the_jam