Top Level Namespace

Defined Under Namespace

Modules: SmartIoC

Instance Method Summary collapse

Instance Method Details

#bean(bean_name, &proc) ⇒ Object

Raises:

  • (ArgumentError)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/smart_ioc/bean.rb', line 1

def bean(bean_name, &proc)
  raise ArgumentError, "name should be a Symbol" if !bean_name.is_a?(Symbol)
  raise ArgumentError, "proc should be provided" if !block_given?

  klass = Class.new do
    include SmartIoC::Iocify
  end

  klass.instance_variable_set(:@anonymous_bean, true)
  klass.instance_exec(&proc)

  str       = SmartIoC::StringUtils
  file_path = caller[0].split(':').first
  package   = klass.instance_variable_get(:@package) || SmartIoC::BeanLocations.get_bean_package(file_path)
  context   = klass.instance_variable_get(:@context) || :default

  if package.nil?
    raise ArgumentError, "package is not defined for bean :#{bean_name}"
  end

  package_mod = str.camelize(package)
  context_mod = str.camelize(context || :default)

  class_name = str.camelize(bean_name)
  klass_name = "#{package_mod}::#{context_mod}::#{class_name}"

  eval(
    %Q(
      module #{package_mod}
        module #{context_mod}
          if constants.include?(:"#{class_name}")
            remove_const :"#{class_name}"
          end
        end
      end

      #{klass_name} = klass
    )
  )

  klass.instance_exec do
    bean(
      bean_name,
      file_path:      file_path,
      scope:          instance_variable_get(:@scope),
      package:        package,
      instance:       instance_variable_get(:@instance) || false,
      factory_method: instance_variable_get(:@factory_method),
      context:        context,
      after_init:     instance_variable_get(:@after_init),
    )
  end

  (klass.instance_variable_get(:@injects) || []).each do |inject|
    klass.register_inject(inject[:bean_name], ref: inject[:ref], from: inject[:from])
  end

  klass
end