-
-
Save havenwood/936c64ae9fae91f18450bf1d3754a12e to your computer and use it in GitHub Desktop.
A contrived example for cthulchu on the #ruby channel
This file contains 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
require 'singleton' | |
class TailCounter | |
include Singleton | |
def initialize | |
@tails = 0 | |
@lock = Mutex.new | |
end | |
def tails | |
@lock.synchronize { @tails } | |
end | |
def increment n = 1 | |
@lock.synchronize { @tails += n } | |
end | |
def decrement n = 1 | |
@lock.synchronize { @tails -= n } | |
end | |
end | |
class Dog | |
TAIL_COUNTER = TailCounter.instance | |
attr_reader :health | |
attr_reader :tails | |
def initialize health: :alive, tails: 1 | |
@health = health | |
@tails = tails | |
TAIL_COUNTER.increment @tails | |
end | |
def lose_a_tail | |
TAIL_COUNTER.decrement | |
@tails -= 1 | |
end | |
def grow_a_tail | |
TAIL_COUNTER.increment | |
@tails += 1 | |
end | |
def pass_away | |
return if @health == :dead | |
TAIL_COUNTER.decrement @tails | |
@health = :dead | |
end | |
def revive | |
return if @health == :alive | |
TAIL_COUNTER.increment @tails | |
@health = :alive | |
end | |
end | |
fluffy_muffin = Dog.new tails: 0 | |
glowing_green = Dog.new tails: 4 | |
sam_the_floof = Dog.new tails: 1 | |
TailCounter.instance.tails | |
#=> 5 | |
sam_the_floof.lose_a_tail | |
#=> 0 | |
TailCounter.instance.tails | |
#=> 4 | |
glowing_green.pass_away | |
#=> :dead | |
TailCounter.instance.tails | |
#=> 0 | |
glowing_green.revive | |
#=> :alive | |
TailCounter.instance.tails | |
#=> 4 | |
glowing_green.grow_a_tail | |
#=> 5 | |
fluffy_muffin.grow_a_tail | |
#=> 1 | |
TailCounter.instance.tails | |
#=> 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment