Skip to content

Instantly share code, notes, and snippets.

@etrepat
Created July 26, 2011 10:56
Show Gist options
  • Save etrepat/1106487 to your computer and use it in GitHub Desktop.
Save etrepat/1106487 to your computer and use it in GitHub Desktop.
Why I don't use class variables in Ruby (or try not to)
class Person
@name = nil
# class-level reader
# cattr_accessor is rails-specific not ruby, and uses class vbles so ...
# may be done like this too:
#
# class << self
# attr_reader :name
# end
#
def self.name
@name
end
end
class A < Person
@name = "John"
end
class B < Person
@name = "Doe"
end
puts A.name
# => John
puts B.name
# => Doe
puts Person.name
# => nil
# class instance variables are enclosed inside the scope of their own class
@name = "Something"
puts A.name
# => John
puts B.name
# => Doe
puts Person.name
# => nil
class Person
@@name = nil
# class-level reader (cattr_accessor is rails-specific, not ruby)
def self.name
@@name
end
end
class A < Person
@@name = "John"
end
class B < Person
@@name = "Doe"
end
puts A.name
# => Doe
puts B.name
# => Doe
puts Person.name
# => Doe
# also, class variables may be modified globally
@@name = "Something"
puts A.name
# => Something
puts B.name
# => Something
puts Person.name
# => Something
@daudt
Copy link

daudt commented Apr 11, 2013

attr_acessor is not a rails specific method. attr_accessible is. Also on your getter method on the first example, self.name is redundant:

def name
@name
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment