开发者

In rails, where to put a constant (variable?) that changes based on the current date?

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 开发者_如何学Goused 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜