Class: Hypo::Container
- Inherits:
-
Object
- Object
- Hypo::Container
- Defined in:
- lib/hypo/container.rb
Instance Attribute Summary collapse
-
#lifetimes ⇒ Object
readonly
Returns the value of attribute lifetimes.
Instance Method Summary collapse
- #add_lifetime(lifetime, name) ⇒ Object
-
#initialize ⇒ Container
constructor
A new instance of Container.
- #register(item, name = nil) ⇒ Object
- #register_instance(item, name) ⇒ Object
- #resolve(name) ⇒ Object
Constructor Details
#initialize ⇒ Container
Returns a new instance of Container.
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/hypo/container.rb', line 12 def initialize @components = {} @lifetimes = {} @mutex = Mutex.new add_lifetime(Lifetime::Transient.new, :transient) add_lifetime(Lifetime::Singleton.new, :singleton) add_lifetime(Lifetime::Scope.new, :scope) register_instance self, :container end |
Instance Attribute Details
#lifetimes ⇒ Object (readonly)
Returns the value of attribute lifetimes.
10 11 12 |
# File 'lib/hypo/container.rb', line 10 def lifetimes @lifetimes end |
Instance Method Details
#add_lifetime(lifetime, name) ⇒ Object
60 61 62 63 64 |
# File 'lib/hypo/container.rb', line 60 def add_lifetime(lifetime, name) @lifetimes[name] = lifetime self end |
#register(item, name = nil) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/hypo/container.rb', line 23 def register(item, name = nil) unless item.is_a?(Class) raise ContainerError, 'Using method "register" you can register only a type. ' \ 'If you wanna register an instance please use method "register_instance".' end component = Component.new(item, self, name) @mutex.synchronize do @components[component.name] = component end @components[component.name] end |
#register_instance(item, name) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/hypo/container.rb', line 38 def register_instance(item, name) if item.is_a?(Class) raise ContainerError, 'Using method "register_instance" you can register only an instance. ' \ 'If you wanna register a type please use method "register".' end @mutex.synchronize do instance = Instance.new(item, self, name) @components[name] = instance end @components[name] end |
#resolve(name) ⇒ Object
52 53 54 55 56 57 58 |
# File 'lib/hypo/container.rb', line 52 def resolve(name) unless @components.key?(name) raise ContainerError, "Component with name \"#{name}\" is not registered" end @components[name].instance end |