Fun with Rails action cache

November 2, 2006 Link to post  Permalink

I had the opportunity to use my action_cache plugin code in a project today. While adding the code to the project, I realized I could do a little better at caching than I had thought when I wrote the code some time ago.

The pages I needed to cache have a different menu, based on whether the user is an admin or not. How can I make this work without resorting to AJAX or client side JavaScript tricks?

I handled this case by implementing a custom fragment_key method. Mine now looks something like this:

1   ActionController::Caching::Actions::ActionCacheFilter.fragment_key = Proc.new {|controller|
2      "AC/#{controller.request.host_with_port}/#{controller.user_is_admin? ? "admin" : "user"}/#{controller.params.sort.join('/').gsub(' ', '-')}"
3    }

Now I have different output cached for admin and non-admin users.

The fragment key generation can include any data your actions depend on for different output. My project uses Matt’s Theme Support plugin and multiple sites can use the same theme, so I can actually change my fragment_key method to something like this:

1   ActionController::Caching::Actions::ActionCacheFilter.fragment_key = Proc.new {|controller|
2      "AC/#{controller.current_theme}/#{controller.user_is_admin? ? "admin" : "user"}/#{controller.params.sort.join('/').gsub(' ', '-')}"
3    }

Even I didn’t realize quite how powerful this feature was.

If anyone is using the action_cache plugin, can you leave a comment so I know who you are! Thanks