Skip to content

Instantly share code, notes, and snippets.

@jasonblanchard
Last active December 20, 2015 03:59
Show Gist options
  • Save jasonblanchard/6067429 to your computer and use it in GitHub Desktop.
Save jasonblanchard/6067429 to your computer and use it in GitHub Desktop.
Dependency Injection
class Animal
def initialize
@sound = "Crickets, crickets..."
end
def make_noise
puts @sound
end
end
class Dog < Animal
def initialize
@sound = "Woof, woof"
end
end
class Cat < Animal
def initialize
@sound = "Meow, puurrr"
end
end
class Cow < Animal
def initialize
@sound = "Moooo"
end
end
class PetAnimal
def initialize(animal = Animal.new)
@animal = animal
end
def pet
@animal.make_noise
end
end
PetAnimal.new.pet # "Crickets, crickets..."
PetAnimal.new(Dog.new).pet # "Woof, woof"
PetAnimal.new(Cat.new).pet # "Meow, puurrr"
PetAnimal.new(Cow.new).pet # "Moooo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment