This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: What's New in Edge Rails: Pluggable Controller Caching
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
It appears that Rails controller will no longer be limited to file-based page and fragment caching. There is a lot of work being done in the 2-1-caching branch of Rails that will let you specify your preferred caching engine in the config file. To date there are the following options:
If none is specified, then ActiveSupport::Cache::MemoryStore will be used.
Write Your Own Controller Cache
Interested in writing your own controller caching mechanism? Here are some basic steps:
1. Implement the Cache Class
The easiest way to write your own cache class is to subclass ActiveSupport::Cache::Store and implement the read, write, delete and delete_matched methods:
moduleActiveSupportmoduleCache# Pluck and store stuff in the ether.# ('Ether' is fictitious - ignore its implementation)classEtherStore < Storedefinitialize(location='//myloc')@ether = Ether.new(location)enddefread(name, options = nil)super@ether.get(name)enddefwrite(name, value, options = nil)super@ether.store(name, value)enddefdelete(name, options = nil)super@ether.remove(name)enddefdelete_matched(matcher, options = nil)super@ether.remove_by_pattern(matcher)endendendend
A few notes:
Invoking super for each method call ensures that the proper messages get logged for each action
If the underlying cache mechanism doesn’t support a specific operation (such as delete_matched), have your implementation just raise an exception: raise "delete_matched not supported by Mechanism"
The options argument passed to each method is taken directly from the various top-level cache methods which now accept an options hash (you now have a method to pass in options applicable to your caching mechanism). I.e.in your view when fragment caching:
Once you have your implementation (and it’s tested, of course), plug it into your app with a simple one-liner in environment.rb:
12
# Or EtherStore.new('//etherloc')ActionController::Base.cache_store = :ether_store, '//etherloc'
There you go, that’s all there is to it.
I’m not sure what the intent is for this functionality, but as of now it only exists in the 2-1-caching branch of rails, I will update this post when it makes it to edge.