Skip to content

Instantly share code, notes, and snippets.

@iain
Created November 15, 2012 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain/4077731 to your computer and use it in GitHub Desktop.
Save iain/4077731 to your computer and use it in GitHub Desktop.
A Quick Dependency Injection Example
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
@robinroestenburg
Copy link

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?

class RetrievesJenkinsInformation

  def initialize(project, options)
    @project = project
    @retrieves_job = options.fetch(:job_retriever)
    @mapper = options.fetch(:build_status_mapper)
  end

  def update
    { :status => @mapper.new(job.color).map }
  end

  def jenkins
    @project.jenkins
  end

  def job
    @retrieves_job.new(jenkins.identifier).retrieve
  end
end

project = ... # ActiveRecord call
options = {
  job_retriever: Jenkins::Job,
  build_status_mapper: MapsJobColorToBuildStatus
}
updated_information = Jenkins::RetrievesJenkinsInformation.new(project, options) 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment