Plasticx Blog

Capable of being shaped or formed

Rails Caching Gotchas

Posted by Mike 10/18/2006 at 12:18PM

I had been experimenting with caching with an action in one of my controllers. The action was slow doing some additional sorting of results gathered from ActiveRecord. I had made sure that I had chosen the best ActiveRecord query and that I was sorting the results in an efficient Ruby way (i.e. in place), but the action was still slow.

I then stumbled upon the caching features in Rails. First I tried action caching then I tried page caching . After each change I restarted my WEBrick instance and didn’t notice an improvement with the caching code.

I wouldn’t see an improvement with the caching in place because the development and testing environment have caching disabled by default.

$ ruby script/server -e development

See the config.action_controller.perform_caching = false setting in your config/environments/development.rb . Rails caching is enabled in production mode.

$ ruby script/server -e production

I ran the application in production mode once to see how well the page caching performed.

I abandoned my caching experiment and went back to working on the action. I then noticed that the page running in WEBrick as seen in the web browser was not behaving the same as in its functional test. I do code by test driven development, so generally I write code, see how it works in the functional test, and see how it looks in the web browser if that’s what the code is for.

It turns out that when the controller was run with page caching
enabled in production mode it functioned properly and wrote out static html. I didn’t expire the page cache in code or employ any kind of sweeper functionality in my code (i.e. I didn’t delete the static files written to the public directory with expire). The controller’s name was “foo” and I was writing a “bar” action thus the static page cache became public/foo/bar.html .

When I abandoned the page cache code and tried out action caching in the development envirnoment I did not detect that the static files still existed. WEBrick did however, it gives preference to a static page over a controller and action with the identical path pattern. But the functional tests don’t test the operating directory environment that a web server is aware of, they only test the controller with mock request and response objects.

Only as my action code changed and I started to notice that the functional test was operating differently what was rendered to the screen did I begin to be aware of my Nuby mistake. I guess I could have also written functional tests on the content in my tags
but I was too Nuby to even think like that (plus screen scrapping is kind of kludgey IMHO ).

Posted in , |

Trackbacks<

Use the following link to trackback from your own site:
http://plasti.cx/trackbacks?article_id=8


Web Statistics