Class: Pcli::Container
- Inherits:
-
Object
- Object
- Pcli::Container
- Defined in:
- lib/pcli/container.rb
Instance Method Summary collapse
-
#initialize ⇒ Container
constructor
A new instance of Container.
- #register(name, type) ⇒ Object
- #register_instance(name, instance) ⇒ Object
- #register_module(m, hierarchy = []) ⇒ Object
- #resolve(name, originator = nil) ⇒ Object
Constructor Details
#initialize ⇒ Container
Returns a new instance of Container.
5 6 7 8 |
# File 'lib/pcli/container.rb', line 5 def initialize @registrations = {} @instances = {} end |
Instance Method Details
#register(name, type) ⇒ Object
10 11 12 |
# File 'lib/pcli/container.rb', line 10 def register(name, type) @registrations[name] = type end |
#register_instance(name, instance) ⇒ Object
14 15 16 |
# File 'lib/pcli/container.rb', line 14 def register_instance(name, instance) @instances[name] = instance end |
#register_module(m, hierarchy = []) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/pcli/container.rb', line 18 def register_module(m, hierarchy = []) m.constants.each do |name| c = m.const_get(name) h = hierarchy.clone h << name.to_s.underscore.downcase next unless c.is_a?(Module) if c.is_a?(Class) registration_name = h.join('.') register registration_name, c end register_module(c, h) end end |
#resolve(name, originator = nil) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/pcli/container.rb', line 33 def resolve(name, originator = nil) originator ||= name return @instances[name] if @instances.key? name raise "Unregistered dependency \"#{name}\"" unless @registrations.key? name registration = @registrations[name] dependencies = {} if registration.respond_to?(:dependencies) dependencies = registration.dependencies.map do |dependency| raise "Circular dependency \"#{dependency}\"" if originator && dependency == originator [dependency.to_sym, resolve(dependency, originator)] end.to_h end @instances[name] = @registrations[name].new(**dependencies) end |