Skip to content

Instantly share code, notes, and snippets.

@gabrielecanepa
Last active April 7, 2020 22:55
Show Gist options
  • Save gabrielecanepa/e7e7978b2b4f8e6b44807957bb7828c2 to your computer and use it in GitHub Desktop.
Save gabrielecanepa/e7e7978b2b4f8e6b44807957bb7828c2 to your computer and use it in GitHub Desktop.
Ruby MVC example @lewagon
# Assign costants at the top of the file.
# Use capital letters for the name, and the #freeze method on the object
PHYLA = %w[Ecdysozoa Lophotrochozoa Radiata Deuterostomia].freeze
class Animal
attr_reader :name
def initialize(name)
@name = name
end
def self.phyla
PHYLA
end
def eat(food)
"#{@name} eats a #{food}"
end
end
# We use one interface for different data types.
# This is called *polimorphism*, see https://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used
require_relative "lion"
require_relative "meerkat"
require_relative "warthog"
animals = []
simba = Lion.new("Simba")
animals << simba
timon = Meerkat.new("Timon")
animals << timon
pumbaa = Warthog.new("Pumbaa")
animals << pumbaa
puts "The sounds of these animals:"
animals.each do |animal|
puts animal.talk
end
puts "\nThe 4 phyla:"
# All animals classes inherit from Animal, so #phyla can be called on any of them!
puts Meerkat.phyla
puts "\nWhat do they eat?"
puts simba.eat("meat")
puts timon.eat("scorpion")
puts pumbaa.eat("pizza")
require_relative "animal"
class Lion < Animal
def eat(food)
"#{super}. Law of the jungle!"
end
end
require_relative "animal"
class Meerkat < Animal
def talk
"#{@name} bark!"
end
end
require_relative "animal"
class Warthog < Animal
def talk
"#{@name} grunt!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment