Caching with Rails

When working with rails, it’s quite useful to change a source file, save it, and reload a web application merely by refreshing the web browser. This had been working great, until one day when my changes didn’t appear in the browser.

I tried clearing the cache on the browser, but it didn’t help. Only when I restarted rails would the change get picked up. Considering that this took a good bit longer than simply refreshing the browser, this caused a serious drain on my productivity and warranted an investigation.

After some initial searching, I discovered the config.cache_classes setting. Here is how the documentation describes it:

config.cache_classes controls whether or not application classes and modules should be reloaded on each request. Defaults to false in development mode, and true in test and production modes. Can also be enabled with threadsafe!.

That sounded promising - all I had to do was disable caching. I went back to development.rb, and here is what I saw:

1
config.cache_classes = false

Caching was already disabled. But Rails still seems to be caching. What’s going on? After reading a blog post by Aaron Patterson, things made a little more sense.

It turns out that the config.threadsafe! setting in the configuration file will turn caching on. This is outlined in the documentation I quote above, but for some reason it didn’t click in my brain until I saw Aaron’s post.

Here is what we had in our configuration:

1
2
config.cache_classes = false
config.threadsafe!

So I was turning caching off, then turning it right back on again with config.threadsafe!. We needed the other threadsafe settings in our application, so we couldn’t just remove that setting, but we also needed caching to be turned off for development.

The solution was simple. I merely had to reverse the two settings in development.rb:

1
2
config.threadsafe!
config.cache_classes = false

And then we had the threadsafe settings that we needed as well as the ability to run in development with the cache disabled.