Home > rails-easycache

rails-easycache

Rails-easycache is a project mainly written in Ruby, it's free.

Easily cache anything in Rails.

= Easycache

Easycache lets you easily cache arbitrary data in your Ruby on Rails applications. The plugin makes use of Rails' built-in fragment caching mechanism to store and retrieve any serializable data. This is especially useful when you want to store data from external sources like LDAP or Web Services, for which Rails does not currently offer an integrated caching mechanism.

Visit http://code.google.com/p/easycache for more information.

=== INSTALLATION

From the command line, cd into your Rails application's root directory and run:

ruby script/plugin install git://github.com/zuk/rails-easycache.git

=== LICENSE

{MIT License}[http://en.wikipedia.org/wiki/MIT_License]

=== EXAMPLES

Once you've installed the plugin, you should be able to do something like this anywhere in your application (in controllers, helpers, etc.):

foo = ['alpha', 'beta', 'delta', 'gamma']

store foo in the cache under the keyname 'greek'

Easycache.write('greek', foo)

retrieve the data stored under keyname 'greek'

foo = Easycache.read('greek')

delete the data stored under keyname 'greek'

Easycache.delete('greek')

In practice, you will probably want to use caching transparently, so that data is pulled from the cache if available, or from the original source otherwise. For example, say you have a function ldap_query() that does a slow LDAP query to retrieve some data. Just wrap this function call inside an Easycache.cache block, like this:

my_data = Easycache.cache('ldap_data') do ldap_query() end

The first time the block runs, it will execute ldap_query(), store its return value in the cache under the key 'ldap_data', and return it for assignment into your my_data variable. The next time it's run, the return value will come from the cache, so the block won't need to be executed.

==== TIME-BASED EXPIRY

The write() and cache() methods both take an optional options hash. Currently the only supported option is :expiry, which will force the cached value to expire after the given number of seconds. For example:

Easycache.write('greek', ['alpha', 'beta'], :expiry => 60)

or

greek = Easycache.cache('greek', :expiry => 60) do ['alpha', 'beta'] end

The above will expire the 'greek' value after 60 seconds. In Rails applications you can use active_support's time extensions to specify the expiry period. For example:

Easycache.write('greek', ['alpha', 'beta'], :expiry => 24.hours)

Previous:KN_May_2010