How to easily cache single AR object?


#1

Hi,

I got a mailer that uses dynamic stylesheets, so when creating an
email I’m doing Style.find_by_name(“newsletter”).

The problem is that it’s fetching the same Style record for each email
it creates and when sending newsletters there can be a lot of them. I
could simply fetch this record in controller and just pass it as a
parameter for deliver_email method, but it doesn’t seem right for me -
I’d like to keep as much as possible inside mailer class.

I can’t also simply put STYLE = Style.find_by_name(“newsletter”) into
Mailer class, because if admin changes the style, the mailer would
still use cached object.

Is there a simple way to do it? This Style object can only be
updated - it can’t be destroyed. I’m using Rails 2.1.1.


#2

If you dont want to get into memcache or other complex solutions you
can do something simple like this:

class StylesCache
include Singleton

def self.by_name(name)
self.instance.by_name(name)
end

def by_name(name)
return @active_style if @active_style && @active_style.name ==
name

@active_style = Style.find_by_name(name)
return @active_style

end
end

style = StylesCache.by_name(“newsletter”)


#3

Thanks for the answer, but I needed a way to clear the “cache” after
the cached object was updated.

Finally made it like this:

class NewsletterMailer
def self.style
@@style ||= fetch_style
end
def self.reload_style
@@style = fetch_style
end
end

and I’m calling NewsletterMailer.reload_style in Style#after_update
callback.