Skip to content

Instantly share code, notes, and snippets.

@nixpulvis nixpulvis/animal.rb
Created Jan 6, 2019

Embed
What would you like to do?
Do the Splits
module Sustenance
def initialize
@stomach = []
super
end
def eat(food)
@stomach << { food: food }
end
def drink(drink)
@stomach << { drink: drink }
end
def poop
digest_to_completion(:food, "can't poop")
end
def pee
digest_to_completion(:drink, "can't pee")
end
private
def digest_to_completion(kind, error_message)
victuals = @stomach.select { |v| v[kind] }
if victuals.empty?
raise error_message
end
@stomach = @stomach - victuals
end
end
class Dog
module Communication
def bark
"Woof"
end
def growl
"Grrr"
end
def wimper
"Rrrr"
end
end
include Communication
include Sustenance
end
class Cat
include Sustenance
end
# Testing!
require 'minitest/autorun'
class TestDog < Minitest::Test
def setup
@dog = Dog.new
end
def test_bark
assert_equal @dog.bark, 'Woof'
end
# Tests ommited...
end
class TestSustenance < Minitest::Test
class Animal
include Sustenance
attr_reader :stomach
end
def setup
@animal = Animal.new
end
def test_eat
assert_empty @animal.stomach
@animal.eat("pepper")
refute_empty @animal.stomach
end
def test_drink
assert_empty @animal.stomach
@animal.drink("slurppy")
refute_empty @animal.stomach
end
def test_poop
@animal.eat("sand")
refute_empty @animal.stomach
@animal.poop
assert_empty @animal.stomach
end
def test_pee
@animal.drink("soda")
refute_empty @animal.stomach
@animal.pee
assert_empty @animal.stomach
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.