I'm using the following low-level caching for the five most recent news articles in my Rails application:
@recent_news = Rails.cache.fetch("recent_news", :expires_in => 1.hour) do
News.order("created_at desc").limit(5)
end
Is there a way to keep this query cached until a new news article is created? I was thinking of manually expiring the cache using an observer, but wasn't sure if there was a way to actually do this, e.g:
class NewsObserver < ActiveRecord::Observer
def after_create
#expire recent_news cache
end
end
What is Low-Level Caching. What Rails calls low level caching is really just reading and writing data to a key-value store. Out of the box, Rails supports an in-memory store, files on the filesystem, and external stores like Redis or memcached. It is called "low level" caching because you are dealing with the Rails.
1.1 Page Caching Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the web server (i.e. Apache or NGINX) without having to go through the entire Rails stack. While this is super fast it can't be applied to every situation (such as pages that need authentication).
clear will clear your app cache. In that case rake tmp:cache:clear will just try to remove files from "#{Rails. root}/tmp/cache" but probably won't actually do anything since nothing is probably being cached on the filesystem.
Rails (as of 2.1) provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk. Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to cache strings.
In Ehcache 3 this is addressed with the ExpiryPolicy interface and its use in controlling the age of cache mappings. Expiry policy is configured at the cache level, so start by defining a cache configuration,
You can use the Cache-Control and Expires headers to control how long objects stay in the cache. Settings for Minimum TTL, Default TTL, and Maximum TTL also affect cache duration, but here's an overview of how headers can affect cache duration:
Browser cache expire TTL is the time that CloudFlare instructs a visitor's browser to cache a resource. Until this time expires, the browser will load the resource from its local cache thus speeding up the request significantly. CloudFlare will respect the headers that you give us from your web server,...
Both Java and XML offer direct support for three types of expiry: this means cache mappings will expire after a fixed duration following their creation, this means cache mappings will expire after a fixed duration following the time they were last accessed. For Java, see org.ehcache.config.builders.ExpiryPolicyBuilder and the XSD for XML.
You can manually expire the cache using the .delete
method:
Rails.cache.delete("recent_news")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With