Module: Kybus::DRY::ResourceInjector
- Defined in:
- lib/kybus/dry/resource_injector.rb
Overview
Provides a method for sending external dependencies to classes, like database connections, configurations, and other objects that can vary but does not modify the class functionality. This class works a decorator to be just extended by classes
class Controller
extend ResourceInjector
end
Instance Method Summary collapse
-
#register(key, subkey, value = nil) ⇒ Object
Provides the interface for sending objects inside the class.
-
#resource(key, subkey = nil) ⇒ Object
Provides the inside interface for fetching the objects that were previously provided from the external world.
-
#resources(key) ⇒ Object
Initialices the resources value and returns the object.
- #unsafe_resource(key, subkey = nil) ⇒ Object
Instance Method Details
#register(key, subkey, value = nil) ⇒ Object
Provides the interface for sending objects inside the class. The resources have a group and sub group. When no group is given, it will be added to the :root group
Examples
Controller.inject(:magic_number, 42)
Controller.inject(:databases, :database_conection, Sequel.connect)
32 33 34 35 36 37 38 39 |
# File 'lib/kybus/dry/resource_injector.rb', line 32 def register(key, subkey, value = nil) if value.nil? value = subkey subkey = key key = :root end resources(key)[subkey] = value end |
#resource(key, subkey = nil) ⇒ Object
Provides the inside interface for fetching the objects that were previously provided from the external world. Also, when no subgroup is given, the key is fetched from :root
Examples
class Controller
def initialize
@magic_number = self.class.resource(:magic_number)
end
def self.factory(id)
db = resource(:databases, :database_conection)
end
end
54 55 56 57 58 59 60 61 62 63 |
# File 'lib/kybus/dry/resource_injector.rb', line 54 def resource(key, subkey = nil) if subkey.nil? subkey = key key = :root end res = resources(key)[subkey] raise("Resource `#{key}::#{subkey}` Not Found") if res.nil? res end |
#resources(key) ⇒ Object
Initialices the resources value and returns the object. This method should not be used from the out context. Resources are grouped by key
20 21 22 23 24 |
# File 'lib/kybus/dry/resource_injector.rb', line 20 def resources(key) @resources ||= {} @resources[key] ||= {} @resources[key] end |
#unsafe_resource(key, subkey = nil) ⇒ Object
65 66 67 68 69 70 71 |
# File 'lib/kybus/dry/resource_injector.rb', line 65 def unsafe_resource(key, subkey = nil) if subkey.nil? subkey = key key = :root end resources(key)[subkey] end |