Rails named_scope and fragment caching

December 4, 2008 Link to post  Permalink

The typical way I’d write code that used fragment caching looked like this.

Contoller

1def foo
2  unless read_fragment('key') do
3    @data = Model.get_some_data
4  end
5end

View

1<% cache('key') do %>
2    <%= do_something_with @data %>
3<% end %>

The fragment caching adds extra work to the controller code to avoid doing the work that didn’t need to be done due to the data being cached. This is kind of messy.

I’ve also written code like this to avoid the above cruftiness

1<% cache('key') do %>
2    <% @data = Model.get_some_data %>
3    <%= do_something_with @data %>
4<% end %>
5

From my previous post about when the named_scope queries actually run it occurred to me that the following code now works correctly.

Contoller

1def foo
2  # No query gets executed here!
3  @data = Model.some_data.since(24.hours.ago).limited(10)
4end

View

1<% cache('key') do %>
2    <%= do_something_with @data %>
3<% end %>

The Named Scope code allows my controllers to once again not care about how the View code works.