[rspec-users] class << self considered harmful... really?

Ben Mabey ben at benmabey.com
Wed Nov 26 20:46:15 EST 2008


Avdi Grimm wrote:
> On Wed, Nov 26, 2008 at 12:17 PM, Matt Wynne <matt at mattwynne.net> wrote:
>   
>>> And class variables are problematic in Rails in development mode because
>>> of class reloading.
>>>       
>> And more generally dangerous for threading reasons, right?
>>     
>
>
> All of the above.  My rule of thumb is: don't use them unless I have a
> very, very good reason.  I can't think of the last time I had that
> good a reason.
>
>   

So.. you are saying that this is preferred:

class State < AR:Base

  def self.names
      @names ||= State.all.map{|s| s.name}
  end

end

to this:

class State < AR:Base

  def self.names
      @@names ||= State.all.map{|s| s.name}
  end

end

Is that correct?

How is using a class instance variable safer from a threading point of 
view?  Do threads not share class instance variables the same way class 
variables would be shared?

-Ben


More information about the rspec-users mailing list