Search code examples
ruby-on-railsamazon-web-servicesrails-activestorage

How to add a custom service to ActiveStorage


I want to add a custom service to ActiveStorage because I want to overwrite the url method of the ActiveStorage::Service::S3Service service so I can use a CloudFront CDN in front of my S3 bucket. I think I will not need the presigned_url params, I will just need the key, because the CloudFront instance will have full read access to the S3 bucket.


Solution

  • Add a class in the ActiveStorage::Service namespace that subclasses ActiveStorage::Service::S3Service. Override the methods you want to override. For example:

    # lib/active_storage/service/cloudfront_s3_service.rb 
    require "active_storage/service/s3_service"
    
    class ActiveStorage::Service::CloudfrontS3Service < ActiveStorage::Service::S3Service
      def url(key, **)
        # ...
      end
    end
    

    Refer to your custom service in config/storage.yml:

    production:
      service: CloudfrontS3
      access_key_id: ""
      secret_access_key: ""
      region: ""
      bucket: ""