Skip to content

Instantly share code, notes, and snippets.

@dsci
Last active December 10, 2015 12:38
Show Gist options
  • Save dsci/4435360 to your computer and use it in GitHub Desktop.
Save dsci/4435360 to your computer and use it in GitHub Desktop.
A Ruby example implementation of DCI (Data Context Interaction). To play around.

The paradigm separates the domain model (data) from use cases (context) and roles that objects play (interaction). DCI is complementary to model–view–controller (MVC). MVC as a pattern language is still used to separate the data and its processing from presentation.

class Account
def initialize
@balance = 500
end
def decrease_balance(amount)
@balance = balance - amount
end
def increase_balance(amount)
@balance = balance + amount
end
def balance
@balance
end
def update_log(message, amount)
p "#{message}: #{amount} Euro. New balance is #{balance}"
end
def self.find(id)
return self.new
end
end
module ContextAccessor
def context
Thread.current[:context]
end
end
module Context
include ContextAccessor
def context=(ctx)
Thread.current[:context] = ctx
end
def context
Thread.current[:context]
end
def in_context
old_context = self.context
self.context = self
res = yield
self.context = old_context
return res
end
end
module SourceAccount
include ContextAccessor
def transfer_out(amount)
raise "Insufficient funds" if balance < amount
decrease_balance(amount)
context.destination_account.transfer_in(amount)
update_log("Transfered out", amount)
end
end
module DestinaAccount
include ContextAccessor
def transfer_in(amount)
increase_balance(amount)
update_log("Transfered in", amount)
end
end
class TransferringMoney
include Context
attr_reader :source_account, :destination_account
def self.transfer(source_account_id, destination_account_id,amount)
source = Account.find(source_account_id)
destination = Account.find(destination_account_id)
TransferringMoney.new(source,destination).transfer(amount)
end
def initialize(source_account, destination_account)
@source_account = source_account.extend(SourceAccount)
@destination_account = destination_account.extend(DestinaAccount)
end
def transfer(amount)
in_context do
source_account.transfer_out(amount)
end
end
end
amount_to_transfer = 200
TransferringMoney.transfer(12,32,amount_to_transfer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment