5

I am working with cache in my Rails project and wants to expire the cache of a particular url. I got the following command to expire fragment corresponding to the URL passed:

ActionController::Base.new.expire_fragment("localhost:3000/users/55-testing-devise/boards/")

I am confused where to put this code in my Rails project so that it gets executed as soon as the url in a text field is added and expire button is clicked.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Swati Aggarwal
  • 1,265
  • 3
  • 19
  • 34

3 Answers3

7

You should probably consider a different approach. Models should not be concerned with how caching works, and traditionally the whole sweeper approach tends to become complex, unwieldy and out of sync with the rest of the code.

Basically, you should never have to expire fragments manually. Instead, you change your cache key/url once your model is updated (so that you have a new cache entry for the new version).

Common wisdom nowadays is to use the Russian Doll Caching approach. The link goes to an article that explains the basics, and the upcoming Rails 4 will contain even better support.

This is probably the best way to go for the majority of standard Rails applications.

averell
  • 3,762
  • 2
  • 21
  • 28
3

The ActionController::Caching::Sweeper is a nice way to do this, its part of Rails observer.

http://api.rubyonrails.org/classes/ActionController/Caching/Sweeping.html

class MyModelSweeper < ActionController::Caching::Sweeper
  observe MyModel

  def after_save(object)
    expire_fragment('...')
  end
end
Charles Barbier
  • 835
  • 6
  • 15
  • I dont want an observer in the model. I have already implemented sweepers in my project. But this when you want the to expire the cache if url without clearing the complete cahe. Is helpers the right place? – Swati Aggarwal Apr 29 '13 at 08:36
2

The expire_fragment won't work, as you don't have the digest added to the key. See DHH here: https://github.com/rails/cache_digests/issues/35

I've posted a related answer about caching a json response: https://stackoverflow.com/a/23783119/252799

Community
  • 1
  • 1
oma
  • 38,642
  • 11
  • 71
  • 99