Rails named_scope and fragment caching
The typical way I’d write code that used fragment caching looked like this.
Contoller
def foo
unless read_fragment('key') do
@data = Model.get_some_data
end
endView
<% cache('key') do %>
<%= do_something_with @data %>
<% 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
<% cache('key') do %>
<% @data = Model.get_some_data %>
<%= do_something_with @data %>
<% end %>From my previous post about when the named_scope queries actually run it occurred to me that the following code now works correctly.
Contoller
def foo
# No query gets executed here!
@data = Model.some_data.since(24.hours.ago).limited(10)
endView
<% cache('key') do %>
<%= do_something_with @data %>
<% end %>The Named Scope code allows my controllers to once again not care about how the View code works.