Websites/app/logical/storage_manager/local.rb

53 lines
1.2 KiB
Ruby
Raw Normal View History

2024-05-03 03:04:43 +00:00
# frozen_string_literal: true
module StorageManager
class Local
DEFAULT_PERMISSIONS = 0o644
2024-05-03 03:04:43 +00:00
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}")
2024-05-03 03:04:43 +00:00
end
def exists?(path)
File.exist?("#{base_path}#{path}")
2024-05-03 03:04:43 +00:00
end
2024-10-13 06:04:55 +00:00
def get(path, &)
File.open("#{base_path}#{path}", "r", binmode: true, &)
2024-05-03 03:04:43 +00:00
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
2024-05-03 03:04:43 +00:00
end
def upload(path, body)
put(path, body)
"#{base_url}#{path}"
2024-05-03 03:04:43 +00:00
end
def url_for(entry)
"#{base_url}#{entry.path}"
2024-05-03 03:04:43 +00:00
end
end
end