BigW Consortium Gitlab

file_mover.rb 1.39 KB
Newer Older
1
class FileMover
2
  attr_reader :secret, :file_name, :model, :update_field
3 4 5 6 7

  def initialize(file_path, model, update_field = :description)
    @secret = File.split(File.dirname(file_path)).last
    @file_name = File.basename(file_path)
    @model = model
8
    @update_field = update_field
9 10 11 12
  end

  def execute
    move
13
    uploader.record_upload if update_markdown
14 15 16 17 18
  end

  private

  def move
19
    FileUtils.mkdir_p(File.dirname(file_path))
20 21 22
    FileUtils.move(temp_file_path, file_path)
  end

23
  def update_markdown
24 25
    updated_text = model.read_attribute(update_field)
                        .gsub(temp_file_uploader.markdown_link, uploader.markdown_link)
26 27 28 29 30 31 32
    model.update_attribute(update_field, updated_text)

    true
  rescue
    revert

    false
33 34 35
  end

  def temp_file_path
36 37
    return @temp_file_path if @temp_file_path

38 39
    temp_file_uploader.retrieve_from_store!(file_name)

40
    @temp_file_path = temp_file_uploader.file.path
41 42 43 44 45 46 47 48 49 50 51
  end

  def file_path
    return @file_path if @file_path

    uploader.retrieve_from_store!(file_name)

    @file_path = uploader.file.path
  end

  def uploader
52
    @uploader ||= PersonalFileUploader.new(model, secret: secret)
53 54 55
  end

  def temp_file_uploader
56
    @temp_file_uploader ||= PersonalFileUploader.new(nil, secret: secret)
57
  end
58 59 60 61 62 63

  def revert
    Rails.logger.warn("Markdown not updated, file move reverted for #{model}")

    FileUtils.move(file_path, temp_file_path)
  end
64
end