# Interesting Class variable problem

**URL:** <https://www.ruby-forum.com/t/interesting-class-variable-problem/166630>\
**Category:** Rails\
**Created:** [April 28, 2009, 12:49am UTC](https://www.ruby-forum.com/t/interesting-class-variable-problem/166630 "2009-04-28T00:49:54Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Commander\_J](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/a8b319/32.png) [@Commander\_J](https://www.ruby-forum.com/u/Commander_J)\
**Post date:** [April 28, 2009, 12:49am UTC](https://www.ruby-forum.com/t/interesting-class-variable-problem/166630/1 "2009-04-28T00:49:54Z")

</div>

class PostOfTheDay  
private

def self.current\_day  
DateTime.now.utc.to\_date  
end

@@current\_post = nil  
@@current\_day = current\_day

def self.get\_random\_post  
posts = Post.all

```
posts[rand(posts.size)]

```

end

public

def self.fetch  
if @@current\_post.nil? || @@current\_day != current\_day  
@@current\_post = get\_random\_post  
@@current\_day = current\_day  
end

```
return @@current_post

```

end  
end

I would expect the class variables @@current\_post and @@current\_day to  
never  
change when not accessed. However, in development mode, on each request,  
a  
different Post is returned because either the Klazz has been garbage  
collected (?) or the initializers

@@current\_post = nil  
@@current\_day = current\_day

have been re-run. But isn’t it required to initialize a class variable  
before usage?

Why is this the default behaviour? Any pointers on a different approach?

---

<div class="post-metadata">

**Author:** ![Commander\_J](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/a8b319/32.png) [@Commander\_J](https://www.ruby-forum.com/u/Commander_J)\
**Post date:** [April 28, 2009, 9:00am UTC](https://www.ruby-forum.com/t/interesting-class-variable-problem/166630/2 "2009-04-28T09:00:44Z")

</div>

On Apr 27, 11:49 pm, Commander J. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> def self.get\_random\_post  
> @@current\_day = current\_day

In development mode classes are cleaned out and loaded from scratch on  
each request (this is why you don’t need to restart the server to see  
changes. In production this isn’t true.

Fred

---

<div class="post-metadata">

**Author:** ![Commander\_J](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/a8b319/32.png) [@Commander\_J](https://www.ruby-forum.com/u/Commander_J)\
**Post date:** [April 28, 2009, 7:17pm UTC](https://www.ruby-forum.com/t/interesting-class-variable-problem/166630/3 "2009-04-28T19:17:54Z")

</div>

Thanks, I just read [Class variable does not retain its value in rails - Rails - Ruby-Forum](http://www.ruby-forum.com/topic/133234) which is also  
very clear.

I’ll just store that Post of the Day inside an ActiveRecord model.

On Tue, Apr 28, 2009 at 8:59 AM, Frederick C. \<
