Question

I'm fragment-caching this fragment:

<% cache('fragment-id') do %>
    <div id="fragment-id">
        <%= render @object %>
    </div> 
<% end %> 

Now, obviously, I need to expire that cache every time an object is updated (speaking from the db perspective).

So I'm supposed to put this line:

expire_fragment('fragment-id') 

...here and there among the controllers, every time an action updates (or saves) an object.

But I'm wondering if there is a DRYer way to do this, like writing some sort of hook in the object model (/app/models/object.rb) which triggers the expire_fragment command on every update (or save).

Is it possible?

EDIT#1:

Maybe I can just overwrite the save method in the object model like this:

def save
    expire_fragment('fragment-id')
    super
end

But, in order for this to work properly, I must be sure that the "save" method is called also by all the other saving methods like *update_attributes*, save!, etc. Is this the case?

Was it helpful?

Solution

You can observe your object with Sweeper, and inside it add hook on update. Read about sweepers there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top