Skip to content

Instantly share code, notes, and snippets.

@pawel2105
Created August 21, 2014 09:48
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 pawel2105/e326905184ea5e00c6b0 to your computer and use it in GitHub Desktop.
Save pawel2105/e326905184ea5e00c6b0 to your computer and use it in GitHub Desktop.
# We create a new class with some sane defaults
class Garden
def initialize(args={})
@trees = args[:trees] || 15
@perimiter = args[:perimiter] || 'fence'
@lawn = args[:lawn] || 'grass'
end
end
>> Garden.new({ trees: '20' })
# { :trees => 20, :perimiter => 'fence', :lawn => 'grass' }
# Someone subclasses Garden and adds specializations, calling on super to use
# the sane defaults from the parent class.
class SmallGarden < Garden
def initialize(args)
@ornaments = args[:ornaments]
super(args)
end
end
>> SmallGarden.new({ ornaments: 'Gnomes' })
# { :ornaments => 'Gnomes', :trees => 15, :perimiter => 'fence', :lawn => 'grass' }
# Then some time later a new team member subclasses Garden but forgets
# to call on super in the initialize. How would you safe-guard this?
class SuperSmallGarden < Garden
def initialize(args)
@catflap = args[:catflap]
end
end
>> SuperSmallGarden.new({ catflap: false })
# { :catflap => false, :trees => nil, :perimiter => nil, :lawn => nil }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment