Created
July 26, 2011 10:56
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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