Vincent
Vincent

Reputation: 16216

Class variables VS constants in Rails models

In my application there can be only one current Event which defaults to the nearest date event. I need to retrieve this event in various places and since it doesn't change it makes sense to cache it. There are two ways of doing it known to me:

class Event < ActiveRecord::Base

  CURRENT_EVENT = Event.where('starts_on >= ?', Time.now).
                  order('starts_on ASC').limit(1).first

  # OR

  def self.current_event
    @@current_event ||= Event.where('starts_on >= ?', Time.now).
                      order('starts_on ASC').limit(1).first
  end

end

Which one would be the best? Or any other alternatives? I know that using @@ class variables is not recommended since they are not thread safe.

Upvotes: 1

Views: 337

Answers (2)

bor1s
bor1s

Reputation: 4113

Neither first nor second approach are correct. If you define constant - it will find Event, actual on Rails initialization process time. Second approach will not cache your record. As for me, this is not so fat data to cache.

Upvotes: 1

jdoe
jdoe

Reputation: 15771

I guess you aren't right about your approach: this way your app will keep your cached value forever. New events won't affect it which is completely wrong. It may be the situation when some event already passed but it is still cached as "current".

By the way: limit(1).first does the same as the only first.

Upvotes: 1

Related Questions