Model caching for pseudo-constant globals


#1

Hi folks,

I have a number of models which do sometimes change, but which are
mostly invariant. These include things like FeatureType, Feature,
Country and SwearWord.

They’re ActiveRecord subclasses, backed by the database, so that they’re
easy for administrators to edit.

Is there a sane way to implement model caching for these, such that I
can do stuff like this in my controllers and models:

Globals.feature_types.each {…}

This would rely on a definition like this in Globals:

def Globals.feature_types
@feature_types ||= FeatureType.find(…)
end

Then I could use after_save and after_update filters on FeatureType and
friends to invalidate the cache like this:

after_save :invalidate_globals

def invalidate_globals
Globals.invalidate_feature_types
end

This would rely on a definition like this in Globals:

def Globals.invalidate_feature_types
@feature_types = nil
end

This kind of thing is pretty common in the J2EE world, where I come
from.

I’ve tried doing this myself, with spectacularly confusing results.
Everything works as expected in my first request, but in my second
request, the objects returned by Globals’ class methods are of the
correct class, but have lost any method I’ve defined on them!

So I’m hoping that there’s a RoR idiom for this. I know about view
caching, but that’s a different beast and doesn’t address the same
problem set. There are templates that I don’t want to cache, the
generation of which would be sped up enormously by some kind of model
caching.

Thanks,
Sheldon.