Constant Cache Plugin

This plugin allows you to cache ActiveRecord instances inside of class constants. When dealing with data inside lookup tables, you no longer have to write code like this:

class Status < ActiveRecord::Base
  PENDING  = 1
  ACTIVE   = 2
  DISABLED = 3
end

Instead, you can simply add the caches_constants method to your class definition:

class Status < ActiveRecord::Base
  caches_constants
end

What Does This Do?

In the first example, to create an account in a pending state you would write code that looks similar to this:

Account.create!(:username => 'preagan', :status => Status.find(Status::PENDING))

When using caches_constants, the plugin pulls all the records in the table and uses the value in the 'name' column to set the constant name. If you have a status with a name of 'Pending', here's some sample output from the console:

>> Status::PENDING
=> #<Status id: 1, name: "Pending">

Since the constant now stores an instance of Status, you would write code like this to create a new account:

Account.create!(:username => 'preagan', :status => Status::PENDING)

Much cleaner, and the call to find only happens when your Rails application loads.

How Do I Install It?

From inside the root directory of your Rails application, run:

./script/plugin install http://svn.extendviget.com/lab/trunk/plugins/caches_constants

or, if you're using Piston:

 piston import http://svn.extendviget.com/lab/trunk/plugins/caches_constants vendor/plugins/caches_constants

Additional Information

See the README file in the root of the plugin directory for additional information and extended usage examples.