Sha256: 49529519880b2c247c08910b64f6125a7d77b66d38c6ad68327392ac23cfa11b

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

module NeetoCommonsBackend
  class Api::DirectUploadsController < ActiveStorage::DirectUploadsController
    protect_from_forgery with: :null_session

    before_action :load_blob!, only: %i[update destroy]

    def create
      @blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_args)
      blob_url = url_for(@blob)
      render json: direct_upload_json(@blob).merge(blob_url:)
    end

    def update
      @blob.update! blob_params
      render status: :ok, json: { notice: "Attachment has been successfully updated.", blob: @blob }
    end

    def destroy
      @blob.attachments.each do |attachment|
        attachment.record&.touch
        attachment.purge
      end
      @blob&.purge
      render status: :ok, json: { notice: "Attachment has been successfully deleted." }
    end

    private

      def load_blob!
        blob_id = ActiveStorage.verifier.verify(params[:id], purpose: :blob_id)
        @blob = ActiveStorage::Blob.find(blob_id)
      rescue ActiveSupport::MessageVerifier::InvalidSignature
        render status: :unprocessable_entity, json: { error: "Attachment signature is not valid." }
      end

      def blob_params
        options = params.require(:blob).permit(:filename)
        if options[:filename].present?
          options.merge!(filename: filename_with_extension(options[:filename]))
        end
        options
      end

      def filename_with_extension(filename)
        file_extension = @blob.filename.extension_with_delimiter
        updated_extension = File.extname(filename)

        if updated_extension == file_extension
          File.basename(filename, ".*") + file_extension
        else
          filename + file_extension
        end
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
neeto-commons-backend-1.0.109 app/controllers/neeto_commons_backend/api/direct_uploads_controller.rb