Rails FileStore cache per environment

I stumbled across and interesting problem today when we were trying to cache the state of login and logout for a CLI in one of our applications. In essence we needed to allow a user to login and maintain login state for subsequent CLI calls and since we were using Thor for our CLI in a rails app the easiest way to do this was using the built in Rails cache.

In order to facilitate caching in development we changed from the default :null_store for development caching to using :file_store so that we could keep state in development mode (which is when we use this cli)

However, we soon ran into issues with tests and development CLI caching conflicting. For example if someone logged in via the CLI and then ran the tests which have the following `before block.`

before do

This ensured that the cache was clear for each new test but it also nuked our development cache.

When using a third party cache store like redis with rails, you can namespace your caches but we weren’t using something like that so what would we do. The solution to namespacing in this context is of course very simple. Just have a different folder for each environment’s cache.

So we added this to `config/application.rb`

config.cache_store = :file_store, Rails.root.join(“tmp/cache/#{Rails.env}”)

That was it. Now our caching in test and development are separate and still not using a third party solution. Now of course your use case may be different and in the case of using redis you can use namespacing in a similar fashion but for us this worked for what we needed.


If you have any feedback, questions, queries, threats or suggestions I’d love to hear from you in the comments. Get in touch!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.