简体   繁体   English

在application.rb中使用Rails.cache

[英]Using Rails.cache in application.rb

I am trying initialize my cache in the application.rb so that it gets populated after the initialization of the app 我正在尝试在application.rb中初始化我的缓存,以便在应用初始化后填充它

My application.rb looks as: 我的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') gives an empty value here Rails.cache.read('key')在此处给出一个空值

but if I put the same code in some other ruby class in rails, it gives the expected output. 但是,如果将相同的代码放在其他红宝石类中,它会提供预期的输出。

Example my_cache.rb 示例my_cache.rb

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

To provide more context, I am also getting this weird behavior my Rails.cache is a ActiveSupport::Cache::NullStore in both application.rb and my_cache.rb, where I think it should be a ActiveSupport::Cache::MemoryStore 为了提供更多的上下文,我也得到了这种奇怪的行为,我的Rails.cache在application.rb和my_cache.rb中都是ActiveSupport::Cache::NullStore NullStore,在这里我认为它应该是ActiveSupport::Cache::MemoryStore

I am using rails 5.1.0 我正在使用Rails 5.1.0

Caching is by default disabled in the dev environment. 默认情况下,在开发环境中禁用缓存。

Therefore I was not able to access the cache. 因此,我无法访问缓存。

Running rake dev:cache creates an empty caching-dev.txt and hence enables caching in the dev environment 运行rake dev:cache创建一个空的caching-dev.txt ,从而在dev环境中启用缓存

This is how development.rb looks like 这是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM