Class: Saviour::LifeCycle::FileUpdater

Inherits:
Object
  • Object
show all
Defined in:
lib/saviour/life_cycle.rb

Instance Method Summary collapse

Constructor Details

#initialize(current_path, file, column, connection) ⇒ FileUpdater

Returns a new instance of FileUpdater.



29
30
31
32
33
34
# File 'lib/saviour/life_cycle.rb', line 29

def initialize(current_path, file, column, connection)
  @file = file
  @column = column
  @current_path = current_path
  @connection = connection
end

Instance Method Details

#uploadObject



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
66
67
68
69
70
71
# File 'lib/saviour/life_cycle.rb', line 36

def upload
  dup_temp_path = SecureRandom.hex

  dup_file = proc do
    Config.storage.cp @current_path, dup_temp_path

    DbHelpers.run_after_commit(@connection) do
      Config.storage.delete dup_temp_path
    end

    DbHelpers.run_after_rollback(@connection) do
      Config.storage.mv dup_temp_path, @current_path
    end
  end

  @new_path = @file.write(
    before_write: ->(path) { dup_file.call if @current_path == path }
  )

  return unless @new_path

  if @current_path && @current_path != @new_path
    DbHelpers.run_after_commit(@connection) do
      Config.storage.delete(@current_path)
    end
  end

  # Delete the newly uploaded file only if it's an update in a different path
  if @current_path.nil? || @current_path != @new_path
    DbHelpers.run_after_rollback(@connection) do
      Config.storage.delete(@new_path)
    end
  end

  [@column, @new_path]
end

#uploaderObject



73
74
75
# File 'lib/saviour/life_cycle.rb', line 73

def uploader
  @file.uploader
end