Skip to content

Instantly share code, notes, and snippets.

@rehanift
Created February 15, 2012 14:43
Show Gist options
  • Save rehanift/1836282 to your computer and use it in GitHub Desktop.
Save rehanift/1836282 to your computer and use it in GitHub Desktop.
Decoupled dependency injection
class AcmeServiceClient
def initialize(http_client, acme_response_translator)
self.http_client = http_client
self.acme_response_translator = acme_response_translator
end
def self.make(dependencies)
instance = self.new(dependencies["http_client"], dependencies["acme_response_translator"])
return instance
end
def self.create()
real_http_client = HttpClient.new()
real_acme_response_translator = AcmeResponseTranslator.new()
instance = self.make({
"http_client" => real_http_client,
"acme_response_translator" => real_acme_response_translator
})
return instance
end
end
describe "AcmeServiceClient"
beforeEach do
mock_http_client = Mock::HttpClient.new()
mock_acme_response_translator = Mock::AcmeResponseTranslator.new()
client = AcmeServiceClient.make({
"http_client" => mock_http_client,
"acme_response_translator" => mock_acme_response_translator
})
end
describe "Placing an order" do
it "makes an HTTP POST request" do
mock_http_client.should_receive(:post).with("/quantity/5")
client.place_order({quantity: 5})
end
end
end
var forwarder = function(listener, sender, logger){
this.listener = listener;
this.sender = sender;
this.logger = logger;
}
forwarder.make = function(dependencies){
dependencies.listener.on("request", function(data){
dependencies.sender.send(data);
dependencies.logger.log("A request was forwarded");
});
return new forwarder(dependencies.listener, dependencies.sender, dependencies.logger);
}
forwarder.create = function(){
var listener = ZeroMqRequestListener.create();
var sender = HttpRequestSender.create();
var logger = FileLogger.create();
return forwarder.make({
listener: listener,
sender: sender,
logger: logger
});
}
forwarder.prototype.close = function(){
this.listener.close();
this.sender.close();
this.logger.log("The forwarder has closed");
this.logger.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment