Skip to content

Instantly share code, notes, and snippets.

@ollie
Created June 26, 2014 15:21
Show Gist options
  • Save ollie/89d2a8d884ebe182ff0a to your computer and use it in GitHub Desktop.
Save ollie/89d2a8d884ebe182ff0a to your computer and use it in GitHub Desktop.
Class-level instance variables
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