Skip to content

Instantly share code, notes, and snippets.

@bansalakhil
Created August 23, 2012 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bansalakhil/3433947 to your computer and use it in GitHub Desktop.
Save bansalakhil/3433947 to your computer and use it in GitHub Desktop.
cattr_accessor vs class_attibute
# 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