2017-05-03 11:26:49 -04:00
|
|
|
class FileMover
|
2017-05-29 03:54:35 -04:00
|
|
|
attr_reader :secret, :file_name, :model, :update_field
|
2017-05-03 11:26:49 -04:00
|
|
|
|
|
|
|
def initialize(file_path, model, update_field = :description)
|
|
|
|
@secret = File.split(File.dirname(file_path)).last
|
|
|
|
@file_name = File.basename(file_path)
|
|
|
|
@model = model
|
2017-05-29 03:54:35 -04:00
|
|
|
@update_field = update_field
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
|
|
|
move
|
2018-03-16 14:34:55 -04:00
|
|
|
|
|
|
|
if update_markdown
|
|
|
|
uploader.record_upload
|
|
|
|
uploader.schedule_background_upload
|
|
|
|
end
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def move
|
2017-05-29 03:54:35 -04:00
|
|
|
FileUtils.mkdir_p(File.dirname(file_path))
|
2017-05-03 11:26:49 -04:00
|
|
|
FileUtils.move(temp_file_path, file_path)
|
|
|
|
end
|
|
|
|
|
2017-05-29 03:54:35 -04:00
|
|
|
def update_markdown
|
2018-02-02 08:59:43 -05:00
|
|
|
updated_text = model.read_attribute(update_field)
|
|
|
|
.gsub(temp_file_uploader.markdown_link, uploader.markdown_link)
|
2017-05-29 03:54:35 -04:00
|
|
|
model.update_attribute(update_field, updated_text)
|
|
|
|
rescue
|
|
|
|
revert
|
|
|
|
false
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def temp_file_path
|
2017-05-29 03:54:35 -04:00
|
|
|
return @temp_file_path if @temp_file_path
|
|
|
|
|
2017-05-03 11:26:49 -04:00
|
|
|
temp_file_uploader.retrieve_from_store!(file_name)
|
|
|
|
|
2017-05-29 03:54:35 -04:00
|
|
|
@temp_file_path = temp_file_uploader.file.path
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def file_path
|
|
|
|
return @file_path if @file_path
|
|
|
|
|
|
|
|
uploader.retrieve_from_store!(file_name)
|
|
|
|
|
|
|
|
@file_path = uploader.file.path
|
|
|
|
end
|
|
|
|
|
|
|
|
def uploader
|
2018-01-29 16:06:17 -05:00
|
|
|
@uploader ||= PersonalFileUploader.new(model, secret: secret)
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def temp_file_uploader
|
2018-01-29 16:06:17 -05:00
|
|
|
@temp_file_uploader ||= PersonalFileUploader.new(nil, secret: secret)
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|
2017-05-29 03:54:35 -04:00
|
|
|
|
|
|
|
def revert
|
|
|
|
Rails.logger.warn("Markdown not updated, file move reverted for #{model}")
|
|
|
|
|
|
|
|
FileUtils.move(file_path, temp_file_path)
|
|
|
|
end
|
2017-05-03 11:26:49 -04:00
|
|
|
end
|