Class: IOC::Container
- Inherits:
-
Object
- Object
- IOC::Container
- Defined in:
- lib/iocx.rb
Instance Method Summary collapse
-
#initialize ⇒ Container
constructor
A new instance of Container.
- #register(key, klass = nil, &block) ⇒ Object
- #release ⇒ Object
- #resolve(key) ⇒ Object
- #resolve_by_type(type) ⇒ Object
- #validate! ⇒ Object
Constructor Details
#initialize ⇒ Container
Returns a new instance of Container.
9 10 11 12 |
# File 'lib/iocx.rb', line 9 def initialize @services = {} @cache = {} end |
Instance Method Details
#register(key, klass = nil, &block) ⇒ Object
14 15 16 17 18 |
# File 'lib/iocx.rb', line 14 def register(key, klass=nil, &block) raise(DuplicateServiceError, "Service '#{key}' has already been registered") if @services.key?(key) raise(RegistrationError, "expected class or block") unless klass || block_given? @services[key] = klass ? klass : block end |
#release ⇒ Object
40 41 42 |
# File 'lib/iocx.rb', line 40 def release @cache = {} end |
#resolve(key) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/iocx.rb', line 20 def resolve(key) raise(UnknownServiceError, "Service '#{key}' not registered") unless @services.key?(key) return @cache[key] if @cache.key?(key) @cache[key] = if @services[key].is_a?(Proc) @services[key].call(self) else dependencies = get_dependencies(@services[key]) resolved_dependencies = dependencies.map{|dependency| resolve(dependency)} @services[key].new(*resolved_dependencies) end end |
#resolve_by_type(type) ⇒ Object
35 36 37 38 |
# File 'lib/iocx.rb', line 35 def resolve_by_type(type) key, _ = @services.find{|key, service| !service.is_a?(Proc) && service <= type} key ? resolve(key) : raise(UnknownServiceError, "Service of type '#{type}' not registered") end |
#validate! ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/iocx.rb', line 44 def validate! missing = [] class_services = @services.values.reject{|service| service.is_a?(Proc)} class_services.each do |service| dependencies = get_dependencies(service) dependencies.each do |dependency| unless @services.key?(dependency) missing << dependency end end end missing.uniq! unless missing.empty? raise(MissingDependenciesError, "missing dependencies: '#{missing.join(', ')}'") end end |