Module: BatchKit::ResourceHelper

Defined in:
lib/batch-kit/resources.rb

Overview

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.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(cls) ⇒ Object

Add automatic disposal of resources on completion of job if included into a job.



179
180
181
182
183
184
185
186
# 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

Instance Method Details

#add_resource(rsrc) ⇒ Object

Register a resource for later clean-up



138
139
140
141
142
# 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

#cleanup_resourcesObject

Dispose of all resources managed by this object.



167
168
169
170
171
172
173
174
# 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_resource(rsrc) ⇒ Object

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.



151
152
153
154
155
156
157
158
159
160
161
162
163
# 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