gitlab-org--gitlab-foss/app/uploaders/records_uploads.rb

70 lines
1.7 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module RecordsUploads
2018-01-29 12:57:34 -05:00
module Concern
extend ActiveSupport::Concern
2018-01-29 12:57:34 -05:00
attr_accessor :upload
2018-01-29 12:57:34 -05:00
included do
after :store, :record_upload
before :remove, :destroy_upload
end
# After storing an attachment, create a corresponding Upload record
#
# NOTE: We're ignoring the argument passed to this callback because we want
# the `SanitizedFile` object from `CarrierWave::Uploader::Base#file`, not the
# `Tempfile` object the callback gets.
#
# Called `after :store`
# rubocop: disable CodeReuse/ActiveRecord
2018-01-29 12:57:34 -05:00
def record_upload(_tempfile = nil)
return unless model
return unless file && file.exists?
Upload.transaction do
uploads.where(path: upload_path).delete_all
2018-06-07 10:01:47 -04:00
upload.delete if upload
2018-01-29 12:57:34 -05:00
self.upload = build_upload.tap(&:save!)
2018-01-29 12:57:34 -05:00
end
end
# rubocop: enable CodeReuse/ActiveRecord
2018-01-29 12:57:34 -05:00
def upload_path
File.join(store_dir, filename.to_s)
end
private
# rubocop: disable CodeReuse/ActiveRecord
2018-01-29 12:57:34 -05:00
def uploads
Upload.order(id: :desc).where(uploader: self.class.to_s)
end
# rubocop: enable CodeReuse/ActiveRecord
def build_upload
2018-01-29 12:57:34 -05:00
Upload.new(
uploader: self.class.to_s,
size: file.size,
path: upload_path,
model: model,
mount_point: mounted_as
2018-01-29 12:57:34 -05:00
)
end
2018-01-29 12:57:34 -05:00
# Before removing an attachment, destroy any Upload records at the same path
#
# Called `before :remove`
# rubocop: disable CodeReuse/ActiveRecord
2018-01-29 12:57:34 -05:00
def destroy_upload(*args)
return unless file && file.exists?
2018-01-29 12:57:34 -05:00
self.upload = nil
uploads.where(path: upload_path).delete_all
end
# rubocop: enable CodeReuse/ActiveRecord
end
end