Forum: Ruby on Rails Model caching for pseudo-constant globals

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9d1310212bb9dfe69ee6b259c7945392?d=identicon&s=25 Sheldon Hearn (sheldonh)
on 2006-04-28 12:53
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.
This topic is locked and can not be replied to.