Class: Hypo::Container

Inherits:
Object
  • Object
show all
Defined in:
lib/hypo/container.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContainer

Returns a new instance of Container.



13
14
15
16
17
18
19
20
21
22
# File 'lib/hypo/container.rb', line 13

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

#componentsObject (readonly)

Returns the value of attribute components.



11
12
13
# File 'lib/hypo/container.rb', line 11

def components
  @components
end

#lifetimesObject (readonly)

Returns the value of attribute lifetimes.



11
12
13
# File 'lib/hypo/container.rb', line 11

def lifetimes
  @lifetimes
end

Instance Method Details

#add_lifetime(lifetime, name) ⇒ Object



63
64
65
66
67
# File 'lib/hypo/container.rb', line 63

def add_lifetime(lifetime, name)
  @lifetimes[name] = lifetime

  self
end

#register(item, name = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hypo/container.rb', line 24

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



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hypo/container.rb', line 39

def register_instance(item, name)
  if %w(attrs attributes).include? name
    raise ContainerError, "Name \"#{name}\" is reserved by Hypo container please use another variant."
  end

  @mutex.synchronize do
    instance = Instance.new(item, self, name)
    @components[name] = instance
  end

  @components[name]
end

#resolve(name, attrs = nil) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/hypo/container.rb', line 52

def resolve(name, attrs = nil)
  if [:attrs, :attributes].include? name
  else
    unless @components.key?(name)
      raise MissingComponentError.new(name)
    end

    @components[name].instance(attrs)
  end
end

#show(component_name) ⇒ Object



69
70
71
# File 'lib/hypo/container.rb', line 69

def show(component_name)
  @components[component_name]
end