lib/nurse/dependency_container.rb in nurse-rb-1.0.0 vs lib/nurse/dependency_container.rb in nurse-rb-2.0.0
- old
+ new
@@ -1,68 +1,71 @@
module Nurse
+ # The dependency container class
class DependencyContainer
class UndefinedDependency < RuntimeError; end
class DependencyAlreadyDefined < RuntimeError; end
- def define(dependency, &block)
+ def initialize
+ @factories = {}
+ @shared_factories = {}
+ @instances = {}
+ end
+
+ def share(dependency, &block)
ensure_undefined(dependency)
- definitions[to_key(dependency)] = block
+ shared_factories[to_key(dependency)] = block
self
end
- def define!(dependency, &block)
- undefine(dependency)
- define(dependency, &block)
+ def set(dependency, &block)
+ ensure_undefined(dependency)
+ factories[to_key(dependency)] = block
+ self
end
def defined?(dependency)
- definitions.has_key?(to_key(dependency))
+ key = to_key(dependency)
+ shared_factories.key?(key) || factories.key?(key)
end
- def get(dependency)
- return nil unless self.defined?(dependency)
-
+ def get(dependency, &_block)
key = to_key(dependency)
- unless instances.has_key?(key)
- instances[key] = definitions[key].call(self)
+ if self.defined?(key)
+ return from_shared_factories(key) || from_factories(key)
end
- instances[key]
+ return yield if block_given?
+
+ fail UndefinedDependency, "'#{dependency}' was not defined"
end
- def fetch(dependency, &block)
- return get(dependency) if self.defined?(dependency)
- return block.call(dependency) if block_given?
- raise UndefinedDependency, "'#{dependency}' was not defined"
+ def add_factory(factory)
+ factory.attach_to(self)
end
- private
+ protected
- def ensure_undefined(dependency)
- if self.defined?(to_key(dependency))
- raise DependencyAlreadyDefined.new(
- "Dependency '#{dependency}' was already defined"
- )
- end
- end
+ attr_reader :factories
+ attr_reader :instances
+ attr_reader :shared_factories
- def instances
- @instances ||= {}
+ def from_shared_factories(key)
+ return unless shared_factories.key?(key)
+ instances[key] ||= shared_factories[key].call(self)
end
- def definitions
- @definitions ||= {}
+ def from_factories(key)
+ factories[key].call(self) if factories.key?(key)
end
- def to_key(object)
- object.to_s.to_sym
+ def ensure_undefined(dependency)
+ return unless self.defined?(dependency)
+ fail DependencyAlreadyDefined,
+ "Dependency '#{dependency}' was already defined"
end
- def undefine(dependency)
- return unless self.defined?(dependency)
- key = to_key(dependency)
- definitions.delete(key)
- instances.delete(key)
+ def to_key(object)
+ object.to_s
end
end
end