CCCPaste

task execution context

# frozen_string_literal: true
class TaskExecutionContext
  attr_reader :resource_type, :resource_ids, :job, :worker

  def initialize(resource_type, resource_ids, job, worker)
    @resource_type = resource_type
    @resource_ids = resource_ids
    @job = job
    @worker = worker
  end

  delegate :set_progress_total!,
           :increment_progress!,
           :set_progress!,
           :succeed!,
           :fail!,
           to: :worker

  def attach_file!(path, filename:, description: nil)
    file = File.open(path)
    @job.files.attach(
      io: file,
      filename: filename,
      metadata: { description: description }
    )
  ensure
    file&.close
  end

  def resources
    @resources ||= @resource_type.constantize.where(id: @resource_ids)
  end

  def each_resource(&block)
    resources.find_each do |resource|
      yield resource
      worker.increment_progress!
    end
  end

  def find_resource(id)
    resources.find(id)
  end

  def resource_count
    @resource_ids.count
  end

  def job_id
    @job.id
  end

  def job_resources
    @job.background_job_resources
  end
end