Class: BgS3uploadable::UploaderJob

Inherits:
ActiveJob::Base
  • Object
show all
Defined in:
app/jobs/bg_s3uploadable/uploader_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(record, attachment) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/jobs/bg_s3uploadable/uploader_job.rb', line 3

def perform(record, attachment)
  key = record.send :"#{attachment}_s3key"
  return if key.blank?

  f = Tempfile.new(SecureRandom.uuid, encoding: 'binary')

  s3 = AWS::S3.new
  bucket = s3.buckets[ENV['S3_BUCKET']]
  obj = bucket.objects[key]

  unless obj.exists?
    # This file has already been auto-deleted. There's nothing we can do
    # anymore.
    record.class.transaction do
      record.send(:write_attribute, :"#{attachment}_s3key", nil)
      record.save validate: false
    end
    return
  end

  obj.read do |chunk|
    f.write chunk
  end
  f.flush

  record.class.transaction do
    record.send(:"#{attachment}=", f)
    record.send(:write_attribute, :"#{attachment}_s3key", nil)

    record.save validate: false
  end
ensure
  if f
    f.close
    f.unlink
  end
end