Class: BatchKit::ResourceManager
- Inherits:
-
Object
- Object
- BatchKit::ResourceManager
- Defined in:
- lib/batch-kit/resources.rb
Overview
Defines a manager for resource types, such as database connections etc. Resource types are registered with this class, which then adds acquisition methods to the ResourceHelper module. These acquisition methods add the acquired objects to a collection managed by the objects of the class that includes the ResourceHelper, and modify the returned resource objects so that they automatically de-register themselves if they are disposed of explicitly.
Class Method Summary collapse
-
.disposal_method(rsrc) ⇒ Object
Returns an unbound method object that represents the method that should be called to dispose of
rsrc
. -
.register(rsrc_cls, helper_mthd, options = {}, &body) ⇒ Object
Register a resource type for automated resource management.
Class Method Details
.disposal_method(rsrc) ⇒ Object
Returns an unbound method object that represents the method that should be called to dispose of rsrc
.
20 21 22 23 |
# File 'lib/batch-kit/resources.rb', line 20 def disposal_method(rsrc) disp_mthd = resource_types[rsrc.class] || resource_types.find{ |rt, _| rt === rsrc }.last rescue nil disp_mthd or raise ArgumentError, "No registered resource class matches '#{rsrc.class}'" end |
.register(rsrc_cls, helper_mthd, options = {}, &body) ⇒ Object
Register a resource type for automated resource management.
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 71 72 73 |
# File 'lib/batch-kit/resources.rb', line 42 def register(rsrc_cls, helper_mthd, = {}, &body) if ResourceHelper.method_defined?(helper_mthd) raise ArgumentError, "Resource acquisition method #{helper_mthd} is already registered" end unless body open_mthd = .fetch(:acquisition_method, :open) body = lambda{ |*args| rsrc_cls.send(open_mthd, *args) } end disp_mthd = .fetch(:disposal_method, :close) if rsrc_cls.method_defined?(disp_mthd) if (m = resource_types[rsrc_cls]) && m.name != disp_mthd raise ArgumentError, "Resource class #{rsrc_cls} has already been registered" + " with a different disposal method (##{m.name})" else resource_types[rsrc_cls] = rsrc_cls.instance_method(disp_mthd) end else raise ArgumentError, "No method named '#{disp_mthd}' is defined on #{rsrc_cls}" end # Define the helper method on the ResourceHelper module. This is # necessary (as opposed to just calling the block from the # acquisition methd) in order to ensure that self etc are set # correctly ResourceHelper.class_eval{ define_method(helper_mthd, &body) } # Now wrap an aspect around the method to handle the tracking of # resources acquired, and event notifications add_aspect(rsrc_cls, helper_mthd, disp_mthd) Events.publish(self, 'resource.registered', rsrc_cls, helper_mthd) end |