Created
November 15, 2012 09:49
-
-
Save iain/4077731 to your computer and use it in GitHub Desktop.
A Quick Dependency Injection Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GetMessageFromQueue | |
def initialize(options) | |
@queue = options.fetch(:queue) | |
end | |
def call | |
@queue.pop | |
end | |
end | |
class RemoteQueue | |
def initialize(settings) | |
@settings = settings | |
end | |
def pop | |
connection.fetch_message | |
end | |
private | |
def connection | |
# do some stuff with the settings | |
end | |
end | |
queue = RemoteQueue.new(url: "http://localhost", token: "abc") | |
get_message = GetMessageFromQueue.new(queue: queue) | |
message = get_message.call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice.
Are you using a Service Locator for setting up the dependencies?
The manual setup (lines #32-33) can get reasonably complicated when you have several dependencies I guess.
I rewrote a piece of code to this style. Would this make sense? I am doubting passing the class instead of passing an instance here (the methods would need an argument then). Passing the instance seems the way to go in this case, what do you think?