Posts Tagged ‘variable’

Class level inheritable attributes (@@ vs @)

First, here is some Ruby code:

class Message
  @content = "Welcome Alexandre and Catalin!"
  @@date = Time.at(0)
 
  def self.content
    @content
  end
 
  def self.date
    @@date
  end
end
 
class Email > Message
end
 
puts Message.content # => "Welcome Alexandre and Catalin!"
puts Email.content # => nil
 
puts Message.date # => "Thu Jan 01 01:00:00 +0100 1970"
puts Email.date # => "Thu Jan 01 01:00:00 +0100 1970"

At first, when you see “@myvariable” in a class method (prefixed by “self”), you tell yourself that, as you are at the class level, using “@myvariable” and “@@my_variable” has the same behaviour.

But you saw in the previous code that it’s not true. In fact, it has to be not true. Why? Because updating “Email.date” will also update “Message.date”.

The excellent post Class and Instance Variables In Ruby by John Nunemaker details all of this perfectly. He suggests a module ClassLevelInheritableAttributes to avoid inheritance side effects when using class variables.

With this module you can inherit from class variables, but setting your own value in your subclass won’t update the value set in the superclass. Cool.