How to Call Expire_Fragment from Rails Observer/Model

How to call expire_fragment from Rails Observer/Model?

Disclaimer: My rails is a bit rusty, but this or something like it should work

ActionController::Base.new.expire_fragment(key, options = nil) 

In Rails, a Sweeper isn't getting called in a Model-only setup

Just a note: you can use cache_sweeper in ApplicationController.

class ApplicationController < ActionController::Base
cache_sweeper :my_sweeper
end

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

def after_update(my_model)
expire_page(...)
end
end

How to get the proper key to use expire_fragment?

I'm not sure if this is by design, or whether there is a bug in Rails. But what is happening is the suffix /dca9add42d461d4c76103c08d12a6571 that's added to the end of the cache key when I use the cache command in my views, is a digest, which you can skip by calling cache like so:

<% cache("my-key", { :skip_digest: true }) %>
html
<% end %>

That way the suffix (digest) gets left off the key.

Now where I think a possible bug (?) is coming in, is that the expire_fragment command doesn't add the digest to the end of the key - so I never actually end up expiring my fragments.

So my answer for now - is to use :skip_digest: true if I want to manually expire them.

expire_fragment caching in rails 4

try change this:

def expire_cache(itinerary)
expire_fragment "itinerary_percentage_#{itinerary.id}"
expire_fragment "city_timeline_#{itinerary.id}"
end

into this:

 def expire_cache(itinerary)
ActionController::Base.new.expire_fragment("itinerary_percentage_#{itinerary.id}", options = nil)
ActionController::Base.new.expire_fragment("city_timeline_#{itinerary.id}", options = nil)
end

Expire fragment in Rails 3 for all locales with cache digests

It seems like the answer is "No way to make cache_digests work with manual expiration", see these answers from DHH.

To work around there are two options:

  1. Tie the key to some model and rely on the key-based expiration: <% cache [I18n.locale, city, "city-list"] do %>

  2. Skip the digest in the cache call, and expire manually like showed in the question: <% cache [I18n.locale, "city-list"], skip_digest: true do %>

Asynchronous cache expiration with rails

You will need to manually expire the cache. Because you're using memcached, you just need any data required to generate the cache keys.

You can then write a delayed job to access the cache directly and delete the required keys.

Here's an example sweeper for Resque:

class UserMemcachedSweeper < ActionController::Caching::Sweeper
observe User

def after_save(user)
Resque.enqueue UserCacheExpiry, user.id
end
end

class UserCacheExpiry
@queue = :cache_expiry

def self.perform(user_id)
Rails.cache.delete("/users/#{user_id}")
end
end


Related Topics



Leave a reply



Submit