Jese Leos

Rails Direct Uploads to A Custom Folder

One of my must-have features for PhrontPage was drag-and-drop direct uploads to a plain Markdown editor. I have always liked this functionality on GitHub issues. Rails ships with Trix support for dropping files on an editor, but that is not how I want to write.

I had bookmarked this example by Jeremy Smith a while ago, and it was a great help to get this feature implemented.

However, after a bit of testing, I quickly found my R2 bucket to be a bit messy and wanted to, at a minimum, direct all my blog uploads to a single folder. Surprisingly, there is not a built-in way to do this.

I created a custom ActiveStorage Service that derives from the S3Service and provides an option to append a folder to all the uploads that go through the service.

require "active_storage/service/s3_service"
module ActiveStorage
  class Service
    class S3WithPrefixService < S3Service

      def path_for(key)
        "uploads/#{key}"
      end

      def object_for(key)
        bucket.object(path_for(key))
      end
      
    end
  end
end

The full PhrontPage implements can be seen here, with code to pull the folder from an ENV variable and handle any extra "/". The one below is just the basics to get started.

Once added to your project, all you have to do is add it to your storage.yml file, and you should be all set.