Skip to content

Instantly share code, notes, and snippets.

@bugant
Last active August 14, 2019 01:53
Show Gist options
  • Save bugant/4483304 to your computer and use it in GitHub Desktop.
Save bugant/4483304 to your computer and use it in GitHub Desktop.
DCI implemented using SimpleDelegator to save method caching
require 'delegate'
class Account < Struct.new(:owner, :amount)
end
class MoneyTransferContext < Struct.new(:source, :destination)
def transfer(amount)
# applico i ruoli ai modelli "stupidi"
source_account = SourceRole.new(source)
destination_account = DestinationRole.new(destination)
# definisco le interazioni tra i ruoli
source_account.draw_money(amount)
destination_account.deposit(amount)
end
class SourceRole < ::SimpleDelegator
def draw_money(amount)
self.amount = self.amount - amount
end
end
class DestinationRole < ::SimpleDelegator
def deposit(amount)
self.amount = self.amount + amount
end
end
end
my_account = Account.new("Stefano", 100.0)
other_account = Account.new("Matteo", 50.0)
MoneyTransferContext.new(my_account, other_account).transfer(10.0)
puts my_account.amount # => 90.0
puts other_account.amount # => 60.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment