# How to easily cache single AR object?

**URL:** <https://www.ruby-forum.com/t/how-to-easily-cache-single-ar-object/151561>\
**Category:** Rails\
**Created:** [October 22, 2008, 11:37pm UTC](https://www.ruby-forum.com/t/how-to-easily-cache-single-ar-object/151561 "2008-10-22T23:37:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [October 22, 2008, 11:37pm UTC](https://www.ruby-forum.com/t/how-to-easily-cache-single-ar-object/151561/1 "2008-10-22T23:37:15Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [October 23, 2008, 2:05am UTC](https://www.ruby-forum.com/t/how-to-easily-cache-single-ar-object/151561/2 "2008-10-23T02:05:51Z")

</div>

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”)

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [October 23, 2008, 2:28pm UTC](https://www.ruby-forum.com/t/how-to-easily-cache-single-ar-object/151561/3 "2008-10-23T14:28:13Z")

</div>

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.
