Created
August 23, 2012 07:51
-
-
Save bansalakhil/3433947 to your computer and use it in GitHub Desktop.
cattr_accessor vs class_attibute
This file contains 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
# cattr_accessor | |
class Base | |
cattr_accessor :settings | |
# def self.settings | |
# @@settings | |
# end | |
# def self.settings=(value) | |
# @@settings = value | |
# end | |
end | |
#Class variable have a tendency to wander from class to class. @@settings class variable can be exposed through inheritance tree. | |
class Subclass < Base | |
end | |
>> Base.settings = 'foo' | |
>> Subclass.settings # => 'foo' | |
>> Subclass.settings = 'bar' | |
>> Base.settings # => 'bar' | |
# class_attribute | |
class Base | |
class_attribute :settings | |
# def self.settings | |
# nil | |
# end | |
# def self.settings? | |
# !!settings | |
# end | |
# def self.settings=(value) | |
# # store value in singleton class | |
# # by redefining `settings` method each time | |
# end | |
end | |
#Settings value is inheritable by subclasses. Subclasses can change their own value and it will not impact base class. | |
class Subclass < Base | |
end | |
>> Base.settings = 'foo' | |
>> Subclass.settings # => 'foo' | |
>> Subclass.settings = 'bar' | |
>> Base.settings # => 'foo' | |
# Above code snippets are extracted from some online content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment