To improve fragment caching efficiency in Rails by only caching the things that change. Use this gem after you have configured as much in-memory caching as possible using standard techniques such as Russian Doll caching.
Add this line to your Gemfile:
gem 'cache_replace'
Add this line to a helper file, likely your ApplicationHelper:
include CacheReplace
This gem allows you to easily cache a partial of static html and replace inner dynamic html. Here is an example scenario:
You have some html that would be cached, except for some uncacheable code nested in the DOM. For example:
= render 'container'
.lots
.of
.htmls
= render 'dynamic'
= complicated_uncacheable_stuff
In the scenario above, you can't cache anything without resorting to madness. With cache_replace
, you can:
= render_cached 'container', replace: 'dynamic'
- cache "container" do
.lots
.of
.htmls
= cache_replace_key 'dynamic'
= complicated_uncacheable_stuff
In the above example, you could also remove the _dynamic.html.haml
file like so:
= render_cached 'container', replace: {dynamic: complicated_uncacheable_stuff}
render_cached
provides 4 calling styles:
render_cached "container", replace: "inner"
render_cached "container", replace: ["inner"]
render_cached "container", replace: {key_name: a_helper_method(object)}
render_cached "container" do
{key_name: a_helper_method(object)}
end
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request