Class: Most::DI::Container

Inherits:
Object show all
Defined in:
lib/most/di/container.rb

Defined Under Namespace

Classes: TrapError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Container

Returns a new instance of Container.



32
33
34
35
36
37
# File 'lib/most/di/container.rb', line 32

def initialize(&block)
  @services = {}
  @current_service = nil

  instance_eval(&block) if block_given?
end

Instance Attribute Details

#servicesObject (readonly)

Returns the value of attribute services.



30
31
32
# File 'lib/most/di/container.rb', line 30

def services
  @services
end

Instance Method Details

#[](name) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/most/di/container.rb', line 77

def [](name)
  result = nil

  name = name.intern()
  service = @services[name]

  unless service.nil?
    result = service[:instance]
    if result.nil?
      instance = service[:block].call()
      unless instance.nil?
        result = service[:instance] = Proxy.new(instance, service[:interfaces])
      end
    end
  end

  result
end

#asset(name, options = {}, &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/most/di/container.rb', line 51

def asset(name, options = {}, &block)
  instance = nil

  path = options[:file]
  unless path.nil?
    instance = YAML.load_file(File.expand_path(path)) rescue nil
  end

  if block_given? or not instance.nil?
    service = get_service(name)

    service[:block]    = block
    service[:instance] = instance
    service[:file]     = path
  end
end

#interface(name, service_name = nil, &block) ⇒ Object



68
69
70
71
72
73
74
75
# File 'lib/most/di/container.rb', line 68

def interface(name, service_name = nil, &block)
  service_name = @current_service if service_name.nil?

  if block_given?
    service = get_service(service_name)
    service[:interfaces][name.intern()] = block unless service.nil?
  end
end

#on_creation(&block) ⇒ Object



47
48
49
# File 'lib/most/di/container.rb', line 47

def on_creation(&block)
  asset(@current_service, &block)
end

#serialize_markedObject



96
97
98
99
100
# File 'lib/most/di/container.rb', line 96

def serialize_marked()
  @services.each do |key, service|
    serialize(service)
  end
end

#service(name, &block) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/most/di/container.rb', line 39

def service(name, &block)
  @current_service = name

  instance_eval(&block) if block_given?

  @current_service = nil
end

#update(service) ⇒ Object



102
103
104
# File 'lib/most/di/container.rb', line 102

def update(service)
  serialize(service) if service[:file]
end