Created
June 26, 2014 15:21
-
-
Save ollie/89d2a8d884ebe182ff0a to your computer and use it in GitHub Desktop.
Class-level instance variables
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 Person | |
class << self | |
# Make it available from the outside | |
attr_reader :traits | |
# This removes duplication in this class and subclasses | |
def init_variables | |
@traits = {} | |
end | |
# Initialize those variables | |
def inherited(subclass) | |
subclass.init_variables | |
end | |
# Regular class method | |
def taste_buds(value) | |
@traits[:taste_buds] = value | |
end | |
end | |
# Person can use those variables too, but doesn't have to | |
# if it's considered "abstract" | |
init_variables | |
# Let's set some | |
taste_buds 30 | |
end | |
class YoungPerson < Person | |
taste_buds 500 | |
end | |
class OldPerson < Person | |
taste_buds 50 | |
end | |
p Person.traits # => {:taste_buds=>30} | |
p YoungPerson.traits # => {:taste_buds=>500} | |
p OldPerson.traits # => {:taste_buds=>50} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment