How to expire fragment cache for objects index on object update

625 views Asked by At

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?

1

There are 1 answers

0
Mikhail Nikalyukin On BEST ANSWER

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