Class: Inject::Injector
- Inherits:
-
Object
- Object
- Inject::Injector
- Defined in:
- lib/inject.rb
Constant Summary collapse
- NULL_SOURCE =
Proc.new {}
Instance Attribute Summary collapse
-
#known ⇒ Object
readonly
Returns the value of attribute known.
Instance Method Summary collapse
- #add_source(source) ⇒ Object
- #call(target, name) ⇒ Object
- #extract_injections(source) ⇒ Object
- #fetch(type, name) ⇒ Object
- #ignore?(type) ⇒ Boolean
-
#initialize(*sources) ⇒ Injector
constructor
A new instance of Injector.
- #prevent_collisions(name) ⇒ Object
- #prevent_unkown_required_args(type, name) ⇒ Object
- #resolve(parameters) ⇒ Object
Constructor Details
#initialize(*sources) ⇒ Injector
Returns a new instance of Injector.
12 13 14 15 |
# File 'lib/inject.rb', line 12 def initialize(*sources) @known = {} sources.each { |source| add_source(source) } end |
Instance Attribute Details
#known ⇒ Object (readonly)
Returns the value of attribute known.
10 11 12 |
# File 'lib/inject.rb', line 10 def known @known end |
Instance Method Details
#add_source(source) ⇒ Object
23 24 25 26 27 28 |
# File 'lib/inject.rb', line 23 def add_source(source) extract_injections(source).each do |name| prevent_collisions(name) known[name] = source.method(name) end end |
#call(target, name) ⇒ Object
17 18 19 20 21 |
# File 'lib/inject.rb', line 17 def call(target, name) method = target.method(name) args = resolve(method.parameters) method.call(*args) end |
#extract_injections(source) ⇒ Object
30 31 32 33 34 35 36 |
# File 'lib/inject.rb', line 30 def extract_injections(source) if source.respond_to?(:injections) source.injections else source.class.instance_methods(false) end end |
#fetch(type, name) ⇒ Object
49 50 51 52 53 54 |
# File 'lib/inject.rb', line 49 def fetch(type, name) known.fetch(name) do |key| prevent_unkown_required_args(type, name) NULL_SOURCE end end |
#ignore?(type) ⇒ Boolean
44 45 46 47 |
# File 'lib/inject.rb', line 44 def ignore?(type) @ignored_types ||= [:block, :rest] @ignored_types.include?(type) end |
#prevent_collisions(name) ⇒ Object
61 62 63 64 |
# File 'lib/inject.rb', line 61 def prevent_collisions(name) return unless known.key?(name) raise Conflict.new("The :#{name} method is defined more than once.") end |
#prevent_unkown_required_args(type, name) ⇒ Object
56 57 58 59 |
# File 'lib/inject.rb', line 56 def prevent_unkown_required_args(type, name) return unless type == :req raise UnknownArg.new("Don't know how to inject :#{name}") end |
#resolve(parameters) ⇒ Object
38 39 40 41 42 |
# File 'lib/inject.rb', line 38 def resolve(parameters) parameters.map do |type, name| fetch(type, name).call unless ignore?(type) end.compact end |