Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active June 18, 2018 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/936c64ae9fae91f18450bf1d3754a12e to your computer and use it in GitHub Desktop.
Save havenwood/936c64ae9fae91f18450bf1d3754a12e to your computer and use it in GitHub Desktop.
A contrived example for cthulchu on the #ruby channel
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