Post navigation

Ruby on Rails Caching And JavaScript Techniques

While implementing caching in a recent rails project I came across some typical caching issues. In a lot of pages the content is same for all users but certain components in them have user specific actions. As an example, I have a page listing all public messages that users have posted(similar to the public timeline in twitter) but actions on those messages are user specific(eg: only owner or admin can delete a message). Also, most of these actions use ajax and the rails authenticity token in them also gets cached resulting in subsequent failures if the session changes. Another issue was that the timestamps in most pages is fuzzy and they become irrelevant if a page gets cached for too long. I could have created separate caches for each user but if the user base really grows managing the caches would become a nightmare and that would still not solve the authenticity token and the timestamp problem. The simplest solution was to use JavaScript, more specifically jQuery.
I have been a big fan of jQuery since I started using it about a year and a half ago and try to use it in all my projects. There is an excellent Rails plugin called jRails that replaces Prototype with jQuery and provides all the default Rails helpers for JavaScript making jQuery even more tempting to use. The examples I use below all use jQuery.

1. Handling User Specific Components

Taking the delete action as explained in the example above, the code in the cached view looks something like this:

If the second parameter is passed(in the case of an admin) the function does nothing, else it iterates over all li elements with class “delete” and removes all elements that do not also have, in this case, the “only_kratos_delete_allowed” class.

2. Handling Rails Authenticity Token

This part describes how to take care of the authenticity token problem:

This code is a slight modification of the code posted here. ajaxSend is jQuery function that is executed before every ajax request is sent and I use it here to replace or append the authenticity token to the request, unless the request is GET or the AUTH_TOKEN variable is not defined.

The datify function iterates over all timestamps(elements with class “timestamps”) and replaces them with fuzzy timestamps. The humane_date function(yanked from here) generates the actual fuzzy timestamps.