Forum: Ruby on Rails How to easily cache single AR object?

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.
2b2b07fe8688479d2559704d4bf8a264?d=identicon&s=25 Szymon Nowak (szimek)
on 2008-10-22 23:37
(Received via mailing list)
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.
6fabb84e727dee98d1277df56458cbac?d=identicon&s=25 Andrew Bloom (Guest)
on 2008-10-23 02:05
(Received via mailing list)
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")
2b2b07fe8688479d2559704d4bf8a264?d=identicon&s=25 Szymon Nowak (szimek)
on 2008-10-23 14:28
(Received via mailing list)
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.
This topic is locked and can not be replied to.