Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Smithy::ServiceLocator module for when constructor injection is not ... #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions lib/smithy/service_locator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
require "smithy/container"

module Smithy
module ServiceLocator
class << self
attr_reader :container

def included(base)
base.extend(ClassMethods)
end

def register_container(container)
@container = container
end
end

module ClassMethods
private

def dependency(name)
define_method name do
ServiceLocator.container.instance(name)
end

private name
end
end
end
end
35 changes: 35 additions & 0 deletions spec/smithy/service_locator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require "smithy/service_locator"

describe Smithy::ServiceLocator do
class Dependency
def value
:expected_result
end
end

class ExampleServiceLocator
include Smithy::ServiceLocator

dependency :foo

def test
foo.value
end
end

let(:container) { Smithy::Container.new }
let(:test_object) { ExampleServiceLocator.new }

before do
container.register(:foo, Dependency)
Smithy::ServiceLocator.register_container(container)
end

it "provides requested dependencies" do
test_object.test.should == :expected_result
end

it "makes the dependencies private" do
test_object.private_methods.should include(:foo)
end
end