Cache-column aims to make it easy to store the return values of functoins in the database for recall later.
First add the following code to set-up the before_save filter and include the rest of the methods:
Next, we need to set-up the columns that hold our cached values. This is accomplished through a migration
script/generate cache_column OBJECT/TABLENAME feild:type
script/generate cache_column listing high_price:float low_price:float number_of_price_points:integer
The above migration will add cache columns of the defined time to the listings table.
Now we need to add our cache column deffinations to the model.
The general format is
cache_column :column_name, options
So for our example we want to add
cache_column :high_price cache_column :low_price cache_column :number_of_price_points
Now this dosn't do much so far other then map the virtual attribute
to the database field
No big deal, but the point is to store complex functions in the database. Lets say the high price attribute isn't so strait forward, and is calculated in the find_high_price function
def find_high_price sleep(10) return '10.05' end
We can now tell the gem to update the cached value every time the object is saved by changing the cache_column deffination to
cache_column :high_price, :on_save => :recheck, :action => :find_high_price
Its fairly self explanitory, but this just tells the gem to recheck the price stored in high_price_cache when the model is saved (or touched). The stored value is retreived from the function named in the :action key
There are a few other options like
cache_column :high_price, :on_save => :blank
cache_column :high_price, :on_save => :recheck, :action => :find_high_price, :update_validation => :high_price_changed
The :on_save => :blank just clears the value when it gets saved… not sure what the point of that is yet.
:update_validation should be set to the name of a function, if that function returns false then the cache column will not be updated.
I would love feedback, and bugs reports.
Limitations / Bugs
*Its my first gem.… so sorry for everything I've done wrong :) *It dosn't store variables yet… Mabey next version. Till then use sanitize
Copyright © 2010 Brian Malinconico, released under the MIT license