Module: SmartIoC::Iocify::ClassMethods

Defined in:
lib/smart_ioc/iocify.rb

Instance Method Summary collapse

Instance Method Details

#bean(bean_name, scope: nil, package: nil, instance: true, factory_method: nil, context: nil) ⇒ Object



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
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/smart_ioc/iocify.rb', line 33

def bean(bean_name, scope: nil, package: nil, instance: true, factory_method: nil, context: nil)
  file_path = caller[0].split(':').first

  bean_definition = SmartIoC.get_bean_definition_by_class(self)

  if bean_definition
    if bean_definition.path == file_path
      # seems that file with bean definition was reloaded
      # lets clear all scopes so we do not have
      container = SmartIoC::Container.get_instance
      container.unregister_bean(self)
      container.force_clear_scopes
    else
      raise ArgumentError, "bean with for class #{self.to_s} was already defined in #{bean_definition.path}"
    end
  end

  bean_definition = SmartIoC.register_bean(
    bean_name:      bean_name,
    klass:          self,
    scope:          scope,
    path:           file_path,
    package_name:   package,
    instance:       instance,
    factory_method: factory_method,
    context:        context
  )

  if bean_definition.is_instance?
    class_eval %Q(
      def initialize
        raise ArgumentError, "constructor based allocation is not allowed for beans. Use ioc container to allocate bean."
      end
    )
  end

  nil
end

#inject(bean_name, ref: nil, from: nil) ⇒ Object

Returns nil.

Raises:

  • (ArgumentError)

    if bean_name is not a Symbol

  • (ArgumentError)

    if ref provided and ref is not a Symbol

  • (ArgumentError)

    if from provided and from is not a Symbol

  • (ArgumentError)

    if bean with same name was injected before



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/smart_ioc/iocify.rb', line 80

def inject(bean_name, ref: nil, from: nil)
  bean_definition = SmartIoC::Container.get_instance.get_bean_definition_by_class(self)

  if bean_definition.nil?
    raise ArgumentError, "#{self.to_s} is not registered as bean. Add `bean :bean_name` declaration"
  end

  bean_definition.add_dependency(
    bean_name: bean_name,
    ref:       ref,
    package:   from
  )

  if bean_definition.is_instance?
    class_eval %Q(
      private
        attr_reader :#{bean_name}
    )
  else
    class_eval %Q(
      class << self
        private
          attr_reader :#{bean_name}
      end
    )
  end

  nil
end