在application.rb中使用Rails.cache

时间:2017-11-10 22:38:52

标签: ruby-on-rails caching

我正在尝试在application.rb中初始化我的缓存,以便在应用初始化后填充它

我的application.rb看起来像:

config.cache_store = :memory_store

config.after_initialize do
    Rails.cache.write('key','value)
    puts Rails.cache.read('key')
end

Rails.cache.read('key')在这里给出一个空值

但如果我将相同的代码放在rails中的其他ruby类中,它会给出预期的输出。

示例my_cache.rb

    Rails.cache.write('key','value')
    puts Rails.cache.read('key') # gives output value

为了提供更多上下文,我也得到了这个奇怪的行为,我的Rails.cache在application.rb和my_cache.rb中都是ActiveSupport::Cache::NullStore,我认为它应该是ActiveSupport::Cache::MemoryStore

我正在使用rails 5.1.0

1 个答案:

答案 0 :(得分:0)

默认情况下,在开发环境中禁用缓存。

因此我无法访问缓存。

运行rake dev:cache会创建一个空的caching-dev.txt,从而在开发环境中启用缓存

这就是development.rb的样子

if Rails.root.join('tmp/caching-dev.txt').exist?
  config.action_controller.perform_caching = true
  config.action_mailer.perform_caching = false
  config.cache_store = :memory_store
  config.public_file_server.headers = {
    'Cache-Control' => 'public, max-age=172800'
  }
else
  config.action_controller.perform_caching = false
  config.action_mailer.perform_caching = false
  config.cache_store = :null_store
end