Sometimes it can be tough to find the right way to clear a cache, especially member routes like :show.

It is easy to do a brute force expire, but sometimes it is best to only clear only what gets updated.

If you are using Action Caching in your rails app, expire_fragment is a versatile method to do so.

Why? because Ruby makes it easy for string interpolation into regular expressions.

The Typical Example

With expire_fragment, you can pass a regex to find the cache files you want to expire, i.e:

def expire_record(record)
  expire_fragment /index/
  expire_fragment /businesses/
  expire_fragment 'main_nav_cache'
end

This works to do a brute force expire of all matching or named views, but it does not behave like a scalpel and expire a single business. Enter %r{}.

The Missing Manual for expire_fragment

%r{} is Ruby's way to create a regular expression and pass variables to it.

%r{/business/#{var.id}} becomes /businesses/45

This means it will only expire the cache that matches yourdomain.com/businesses/45.

Or if you are using to_param: yourdomain.com/businesses/45-business-name.

Or if you are using a slug: yourdomain.com/businesses/business-slug.

Back to the Sweeper

By using %r{}, you can build a regular expression and pass the relevant data needed to properly expire as little as possible.

def expire_record(record)
  expire_fragment %r{businesses\/#{record.id}}
  expire_fragment /index/
end

Now all the index views and only the individual view for the business gets expired.

This little trick could be the difference of 5-15ms or more per update depending on how many records are in your database.