Websites/app/logical/storage_manager/local.rb

53 lines
1.2 KiB
Ruby

# frozen_string_literal: true
module StorageManager
class Local
DEFAULT_PERMISSIONS = 0o644
attr_reader :base_url, :base_path
def initialize(base_url:, base_path:)
@base_url = base_url
@base_path = base_path
end
def delete(path)
return unless exists?(path)
File.delete("#{base_path}#{path}")
end
def exists?(path)
File.exist?("#{base_path}#{path}")
end
def get(path, &)
File.open("#{base_path}#{path}", "r", binmode: true, &)
end
def put(path, io)
temp = "#{base_path}#{path}-#{SecureRandom.uuid}.tmp"
FileUtils.mkdir_p(File.dirname(temp))
io.rewind
bytes_copied = IO.copy_stream(io, temp)
raise("store failed: #{bytes_copied}/#{io.size} bytes copied") if bytes_copied != io.size
FileUtils.chmod(DEFAULT_PERMISSIONS, temp)
File.rename(temp, "#{base_path}#{path}")
rescue StandardError => e
FileUtils.rm_f(temp)
raise(e)
ensure
FileUtils.rm_f(temp) if temp
end
def upload(path, body)
put(path, body)
"#{base_url}#{path}"
end
def url_for(entry)
"#{base_url}#{entry.path}"
end
end
end