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
end

View

<% 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)
end

View

<% 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.

This entry was posted on Fri, 05 Dec 2008 05:12:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment .


Comments

Leave a response

Leave a comment