And you thought all the clever caching names were taken.
What is it
ActsAsCachola is a plugin that lets you cache any class method by simply prepending ‘cachola_’ to the method name when calling it. Here’s how it works:
Given the following model:
class Internet < ActiveRecord::Base
acts_as_cachola
def self.get_a_million_numbers
1.upto(1_000_000).inject([]){ |numbers, x| numbers << x }
end
end
Now you can call the method, ‘cachola_get_a_million_numbers,’ and the return value of ‘get_a_million_numbers’ will be cached automatically.
Note that if the method accepts arguments, each unique call will have its own key in the cache. For example:
class Internet < ActiveRecord::Base
acts_as_cachola
def self.get_numbers(to_number)
1.upto(to_number).inject([]){ |numbers, x| numbers << x }
end
end
Calling Internet.cachola_get_numbers(100) and Internet.cachola_get_numbers(500) will result in two keys (with different values) stored in the cache.
The cached method is then expired automatically when the class in which the plugin has been included is saved or destroyed. It’s restored to the cache the next time it’s called.
Now, what if your Internet class method ‘get_a_million_numbers’ depends on other objects getting saved or destroyed? That’s the other thing I wanted to make easier. Rather than setting up observers or sweepers, you can add the following to the other model:
class WhereAmI < ActiveRecord::Base acts_as_cachola_notifier => [:internet] end
Now when your WhereAmI model is ether saved or destroyed, the cached methods in the Internet model will be deleted.
Installation
script/plugin install git://github.com/rbrant/acts_as_cachola.git
Where is this going from here?
Not sure. It does what I need it to do right now. It’s something I’ve found myself doing on two different projects that I thought would just make my life easier.
Project Info
ActsAsCachola is hosted on Github: http://github.com/rbrant/acts_as_cachola, where your contributions, forkings, comments and feedback are greatly appreciated. Please do add tests if you want me to pull in any changes.