Skip to content

Instantly share code, notes, and snippets.

@armandofox
Created May 11, 2021 16:39
Show Gist options
  • Save armandofox/d3ea5309672163c64674b21033c9106c to your computer and use it in GitHub Desktop.
Save armandofox/d3ea5309672163c64674b21033c9106c to your computer and use it in GitHub Desktop.
demeter_example.rb
# This example is adapted from Dan Manges's blog, dcmanges.com
class Wallet ; attr_accessor :credit_balance ; end
class Moviegoer
attr_accessor :wallet
def initialize
# ...setup wallet attribute with correct credit balance
end
end
class MovieTheater
def collect_money(moviegoer, due_amount)
# VIOLATION OF DEMETER (see text)
if moviegoer.wallet.credit_balance < due_amount
raise InsufficientFundsError
else
moviegoer.wallet.credit_balance -= due_amount
@collected_amount += due_amount
end
end
end
# Imagine testing the above code:
describe MovieTheater do
describe "collecting money" do
it "should raise error if moviegoer can't pay" do
# "Mock trainwreck" is a warning of a Demeter violation
wallet = double('wallet', :credit_balance => 5.00)
moviegoer = double('moviegoer', :wallet => wallet)
expect { @theater.collect_money(moviegoer, 10.00) }.
to raise_error(...)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment