Created
May 15, 2014 13:40
-
-
Save meltingice/ea3547c0023321786b7a to your computer and use it in GitHub Desktop.
Ruby: Initializing class instance variables with default values for all subclasses
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
class ParentClass | |
@foo = "bar" | |
class << self | |
attr_accessor :foo | |
def inherited(subclass) | |
subclass.instance_variable_set :@foo, "bar" | |
super | |
end | |
end | |
end | |
class ChildClass < ParentClass | |
end |
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
ParentClass.foo | |
#=> "bar" | |
ChildClass.foo | |
#=> "bar" | |
# Change the value for ChildClass only | |
ChildClass.foo = "look at me" | |
ChildClass.foo | |
#=> "look at me" | |
ParentClass.foo | |
#=> "bar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment