Last active
April 8, 2018 02:48
-
-
Save hannestyden/2af1755fc5c9e7012c76 to your computer and use it in GitHub Desktop.
Inheritence, mix-ins, composotion
This file contains hidden or 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
# Composition | |
class Eat | |
def do_it | |
puts 'Nom, nom ...' | |
end | |
end | |
class Say | |
def do_it | |
puts '...' | |
end | |
end | |
class Fly | |
def do_it | |
puts 'Flap, flap with wings and fly away ...' | |
end | |
end | |
class Swim | |
def do_it | |
puts 'Blub, blub. Swim, swim away ...' | |
end | |
end | |
class Walk | |
def do_it | |
puts 'Schlurf, schlurf. Walk, walk away ...' | |
end | |
end | |
class Cannot | |
def do_it | |
fail "Sorry I can't :'(" | |
end | |
end | |
class Bird < Struct.new(:fly, :eat, :walk, :swim) | |
end | |
class Robin < Bird; end | |
class Crow < Bird; end | |
class Duck < Bird | |
def initialize | |
super(Fly.new, Eat.new, Walk.new, Swim.new) | |
end | |
end | |
class Hawk < Bird | |
def initialize | |
super(SuperFly.new, Eat.new, Walk.new, Cannot.new) | |
end | |
end | |
class Ostridge < Bird | |
def initialize | |
super(Cannot.new, Eat.new, Run.new, Cannot.new) | |
end | |
end | |
class Turkey < Bird | |
def initialize | |
super(Cannot.new, Eat.new, Walk.new, Cannot.new) | |
end | |
end | |
class Penguin < Bird | |
end | |
# duck = Duck.new; duck.fly.do_it; duck.eat.do_it; duck.walk.do_it; duck.swim.do_it | |
turkey = Turkey.new | |
turkey.walk.do_it rescue $! # => nil | |
turkey.fly.do_it rescue $! # => #<RuntimeError: Sorry I can't :'(> | |
turkey.swim.do_it rescue $! # => #<RuntimeError: Sorry I can't :'(> | |
# >> Schlurf, schlurf. Walk, walk away ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment