I'm trying to use redis-store as my Rails 3 cache_store. I also have an initializer/app_config.rb which loads a yaml file for config settings. In my initializer/redis.rb I have:
MyApp::Application.config.cache_store = :redis_store, APP_CONFIG['redis']
However, this doesn't appear to work. If I do:
Rails.cache
in my rails console I can clearly see it's using the
ActiveSupport.Cache.FileStore
as the cache store instead of redis-store. However, if I add the config in my application.rb file like this:
config.cache_store = :redis_store
it works just fine, except the app config initializer is loaded after application.rb, so I don't have access to APP_CONFIG.
Has anyone experienced this? I can't seem to set a cache store in an initializer.
Had the same problem and setting
RAILS_CACHE
toMyApp::Application.config.cache_store
fixed it as well.I tried the following and it works out.
In the original setup you had, does it help if you change:
to:
?
After some research, a probable explanation is that the initialize_cache initializer is run way before the rails/initializers are. So if it's not defined earlier in the execution chain then the cache store wont be set. You have to configure it earlier in the chain, like in application.rb or environments/production.rb
My solution was to move the APP_CONFIG loading before the app gets configured like this:
and then in the same file:
Another option was to put the cache_store in a before_configuration block, something like this:
The
config/initializers
are run after theRails.cache
is initialized, but afterconfig/application.rb
andconfig/environments
.Configuration in config/application.rb or environments
Thus, one solution would be to configure the cache in
config/application.rb
orconfig/environments/*.rb
.Configuration in config/initializers/cache.rb
If the cache should be configured in an initializer intentionally, this can be done by setting
Rails.cache
manually after the configuration:Add a spec
In order to make sure it worked, add a spec like this:
Further information
Rails.cache
is set here during the application bootstrap: https://github.com/rails/rails/blob/5-0-stable/railties/lib/rails/application/bootstrap.rb#L62L70. The redis store does not respond to:middleware
. Thus, we can leave out the additional lines.In the initializer
REDIS ||= Rails.configuration.redis_client
In application.rb