Warning… please leave if you are not a geek. Consider leaving if you’re not a Ruby/Rails geek.
I am working on a project at work and one of the components is a set of sidewide announcements.
class Announcement < ActiveRecord::Base validates_presence_of :title, :body def self.active(time= DateTime.now) @active ||= self.find(:all, :conditions => ["start_at <= ? and end_at >= ? and active=?", time, time, true], :order => "start_at desc") end end
And all seemed to work on my development box. Then I noticed that when we went to production, that the announcements never seemed to go in and out of “active” state like they should. The application listed them as inactive, but they were always shown in the ‘announcements/_active’ partial. Hmm.
The problem is in using an instance variable inside a class method. The instance variable is now an instance of the Announcement Class object, not the Announcement object, so as soon as Rails was fired up, it would load up the active announcements and then that instance variable would stick around until the app got restarted.
But how can you properly cache items within class-level methods? Well, you can always use the Rails cache:
class Announcement < ActiveRecord::Base validates_presence_of :title, :body def self.active(time= DateTime.now) Rails.cache.fetch('Announcements::active', :expires => 30.minutes) do self.find(:all, :conditions => ["start_at <= ? and end_at >= ? and active=?", time, time, true], :order => "start_at desc") end end end
Ahh… a rookie mistake, but one that I hope helps others.

Friday, 24. July 2009
BHLASHADGLHAT YUCK, boring blog post, more kids or other fun stuff.
Friday, 24. July 2009
OK, the last comment was Amber but then I made her go back and actually let me read the post. So here’s MY comment – it reminds me of a similar problem I have with ehntweirtw where the cleknwoe is supposed to be a part of toehowhr but in fact it’s a different oswideto entirely. It turns out that tehlwit is defined by tehtbhehhw and so the whole entire woeifjowefiopw is actually a subset/minor caste of aosdingoindg which (of course!) poses problems with enifne when you’re working in digohdi. Cool, huh?