diff --git a/app/models/site/index.rb b/app/models/site/index.rb index 71c442c1..d66c5272 100644 --- a/app/models/site/index.rb +++ b/app/models/site/index.rb @@ -80,6 +80,16 @@ class Site end end + # Encuentra todos los archivos estáticos a reindexar + # + # @return [Array] + def indexable_static_files + @indexable_static_files ||= + diff_with_head.each_delta.select do |delta| + delta.old_file[:path].start_with? 'public/' + end + end + # Elimina los artículos eliminados o que cambiaron de ubicación # del índice def remove_deleted_posts! @@ -94,6 +104,45 @@ class Site end end + # Elimina de ActiveStorage los archivos borrados, renombrados o + # modificados, para poder recalcular su contenido y nueva + # ubicación. + # + # Los renombrados o modificados se vuelven a crear en + # reindex_modified_static_files! + def remove_deleted_or_renamed_static_files! + indexable_static_files.select do |delta| + delta.deleted? || delta.modified? || delta.renamed? + end.each do |delta| + key = blob_service.key_from_path(delta.old_file[:path]) + + static_files.blobs.find_by(service_name: name, key: key).tap do |blob| + next unless blob + + transaction do + static_files.where(blob_id: blob.id).destroy_all + blob.destroy + end + end + end + end + + # Reindexa los archivos estáticos modificados + def reindex_modified_static_files! + indexable_static_files.select do |delta| + MODIFIED_STATUSES.include?(delta.status) || delta.renamed? + end.each do |delta| + transaction do + path = blob_service.absolute_path_for(delta.new_file[:path].sub(%r{\Apublic/}, '')) + key = blob_service.key_from_path(path) + pathname = Pathname.new(path) + blob = ActiveStorage::Blob.create_after_unfurling!(key: key, io: pathname.open, filename: pathname.basename, service_name: name) + + ActiveStorage::Attachment.create!(name: 'static_files', record: self, blob: blob) + end + end + end + # Reindexa artículos que cambiaron de ubicación, se agregaron # o fueron modificados def reindex_modified_posts!