module BatchKit::ResourceHelper
A module that can be included in a class to provide resource acquisition with automated resource cleanup.
Resources acquired via this module are tracked, and can be disposed of when no longer needed via a call to the cleanup_resources
method.
The benefits of including and using ResourceHelper
module:
-
Resource acquisition can be setup to use a common configuration process, such as obtaining connection details from a shared configuration file.
-
All resources obtained by an object can be freed when the object is done with them by calling the
cleanup_resources
.
Public Class Methods
Add automatic disposal of resources on completion of job if included into a job.
# File lib/batch-kit/resources.rb, line 179 def self.included(cls) if (defined?(BatchKit::Job) && BatchKit::Job == cls) || (defined?(BatchKit::ActsAsJob) && cls.include?(BatchKit::ActsAsJob)) Events.subscribe(BatchKit::Job::Run, 'post-execute') do |run, job_obj, ok| job_obj.cleanup_resources end end end
Public Instance Methods
Register a resource for later clean-up
# File lib/batch-kit/resources.rb, line 138 def add_resource(rsrc) # Ensure we know how to dispose of this resource ResourceManager.disposal_method(rsrc) (@__resources__ ||= Set.new) << rsrc end
Dispose of all resources managed by this object.
# File lib/batch-kit/resources.rb, line 167 def cleanup_resources if @__resources__ @__resources__.clone.reverse_each do |rsrc| dispose_resource(rsrc) end @__resources__ = nil end end
Dispose of a resource.
This method will be called automatically whenever a resource is closed manually (via a call to the resources normal disposal method, e.g. close), or when cleanup_resources
is used to tidy-up all managed resources.
# File lib/batch-kit/resources.rb, line 151 def dispose_resource(rsrc) disp_mthd = ResourceManager.disposal_method(rsrc) @__resources__.delete(rsrc) if Events.publish(rsrc, 'resource.pre-disposal') begin disp_mthd.bind(rsrc).call Events.publish(rsrc, 'resource.disposed') rescue Exception => ex Events.publish(rsrc, 'resource.disposal-failed', ex) raise end end end