Sha256: f1dec14653bc596521dc4c2145694ef0524772ed16aa5ead0425e785c1489d0d

Contents?: true

Size: 1.19 KB

Versions: 5

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

module MobileWorkflow
  class AddAttachmentJob < ApplicationJob
    def perform(object, object_key, attribute_name)
      object.send("#{attribute_name}=", active_record_blob_from_s3(object_key))
      Rails.logger.warn "Error saving object: #{object} #{object.errors.full_messages}" unless object.save
    rescue NoMethodError => e
      Rails.logger.warn "Error attaching object: #{e.message}"
    end

    private

    def active_record_blob_from_s3(object_key)
      # etag cannot be used as the MD5 checksum when doing multi-part uploads
      s3_object = s3_bucket.object(object_key)
      base64_digest = hex_to_base64_digest(s3_object.etag.delete('"'))
      ActiveStorage::Blob.create! key: s3_object.key, filename: s3_object.key, byte_size: s3_object.size,
                                  checksum: base64_digest, content_type: s3_object.content_type
    end

    def s3_bucket
      Aws::S3::Resource.new(region: ENV['AWS_REGION'], access_key_id: ENV['AWS_ACCESS_ID'],
                            secret_access_key: ENV['AWS_SECRET_KEY']).bucket(ENV['AWS_BUCKET_NAME'])
    end

    def hex_to_base64_digest(hexdigest)
      [[hexdigest].pack('H*')].pack('m0')
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mobile_workflow-0.12.2 app/jobs/mobile_workflow/add_attachment_job.rb
mobile_workflow-0.12.1 app/jobs/mobile_workflow/add_attachment_job.rb
mobile_workflow-0.12.0 app/jobs/mobile_workflow/add_attachment_job.rb
mobile_workflow-0.11.1 app/jobs/mobile_workflow/add_attachment_job.rb
mobile_workflow-0.11.0 app/jobs/mobile_workflow/add_attachment_job.rb