5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-07-03 00:16:08 +00:00

subir directamente los archivos a la base de datos

cuando subimos un archivo usando attach en realidad estábamos generando
una copia y dejándola huérfana en el repositorio del sitio.  usando blob
podemos imitar un servicio de subida de archivos sin generar io
innecesario.
This commit is contained in:
f 2022-07-15 19:32:06 -03:00
parent 83384b686a
commit 6c62c20572

View file

@ -68,18 +68,8 @@ class MetadataFile < MetadataTemplate
when ActionDispatch::Http::UploadedFile
site.static_files.last if site.static_files.attach(value['path'])
when String
if (blob_id = ActiveStorage::Blob.where(key: key_from_path, service_name: site.name).pluck(:id).first)
site.static_files.find_by(blob_id: blob_id)
elsif path? && pathname.exist? && site.static_files.attach(io: pathname.open, filename: pathname.basename)
site.static_files.last.tap do |s|
s.blob.update(key: key_from_path)
end
else
raise ArgumentError, 'No se pudo subir el archivo'
end
site.static_files.find_by(blob_id: blob_id) || migrate_static_file!
end
rescue ArgumentError => e
ExceptionNotifier.notify_exception(e, data: { site: site.name, path: value['path'] })
end
# Obtiene la ruta absoluta al archivo
@ -95,7 +85,7 @@ class MetadataFile < MetadataTemplate
#
# @return [String]
def key_from_path
pathname.dirname.basename.to_s
@key_from_path ||= pathname.dirname.basename.to_s
end
def path?
@ -148,4 +138,32 @@ class MetadataFile < MetadataTemplate
def no_file_for_description?
!path? && description?
end
# Obtiene el id del blob asociado
#
# @return [Integer,nil]
def blob_id
@blob_id ||= ActiveStorage::Blob.where(key: key_from_path, service_name: site.name).pluck(:id).first
end
# Genera el blob para un archivo que ya se encuentra en el
# repositorio y lo agrega a la base de datos.
#
# @return [ActiveStorage::Attachment]
def migrate_static_file!
raise ArgumentError, 'El archivo no existe' unless path? && pathname.exist?
Site.transaction do
blob =
ActiveStorage::Blob.create_after_unfurling!(key: key_from_path,
io: pathname.open,
filename: pathname.basename,
service_name: site.name)
ActiveStorage::Attachment.create!(name: 'static_files', record: site, blob: blob)
end
rescue ArgumentError => e
ExceptionNotifier.notify_exception(e, data: { site: site.name, path: value['path'] })
nil
end
end