Class: BetterRecord::ResizeBlobImageJob

Inherits:
ApplicationJob show all
Defined in:
app/jobs/better_record/resize_blob_image_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(**params) ⇒ Object



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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'app/jobs/better_record/resize_blob_image_job.rb', line 5

def perform(**params)
  begin
    if record = params[:model].constantize.find_by(params[:query].deep_symbolize_keys)
      name = params[:attachment].to_sym
      blob = record.__send__(name).blob
      tmp = Tempfile.new
      tmp.binmode
      tmp.write(blob.service.download(blob.variant(blob.filename.to_s =~ /-resized/ ? {resize: '70%'} : params[:options]).processed.key))
      tmp.flush
      tmp.rewind

      blob.analyze if blob.filename.to_s =~ /-resized/

      attachment = ActionDispatch::Http::UploadedFile.new(
        tempfile: tmp,
        filename: blob.filename.to_s.sub(/(\.[^.]*)$/, '-resized\1').sub(/(-resized)+/, '-resized'),
        type: blob.content_type
      )

      begin
        record.
          __send__ :delete_attachment, name, true

        record.
          reload.
          __send__(name).
          attach(attachment)
      rescue
        puts "Attachment No Longer Exists"
        puts $!.message
        puts $!.backtrace
      end

      puts "\n\nSAVED IMAGE\n\n"
      begin
        if params[:backup_action].present?
          record.class.find_by(params[:query]).__send__(params[:backup_action].to_sym)
        end
      rescue
        puts "BACKUP ACTION FAILED"
        puts $!.message
        puts $!.backtrace
      end
      begin
        puts "\n\n PURGING BLOB \n\n"
        puts "blob exists? #{blob = ActiveStorage::Blob.find_by(id: blob.id).present?}"
        blob.purge if blob.present?
        puts "\n\n FINISHED PURGING BLOB \n\n"
      rescue
      end
    else
      raise ActiveRecord::RecordNotFound
    end
    return true
  rescue
    "ERROR RESIZING IMAGE"
    puts $!.message
    puts $!.backtrace.first(25)
    return false
  end
end