How to add a custom service to ActiveStorage

徘徊边缘 提交于 2021-01-21 04:37:04

问题


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.


回答1:


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: ""



回答2:


For anyone thats interested, I had a similar issue where by I wanted to use the same flat, single bucket storage, that the S3Service uses. Its simple enough once you know how:

require "active_storage/service/disk_service"

# S3 uses a flat folder structure, so mimic that so we an sync files and databases
module ActiveStorage
  class Service
    class FlatDiskService < DiskService
      private

      def folder_for(_key)
        "/"
      end
    end
  end
end

And the config is as follows:

local:
   service: FlatDisk
   root: <%= Rails.root.join("storage") %>

Edit: I've updated the answer with the amended version that works in Rails 6.



来源:https://stackoverflow.com/questions/50782477/how-to-add-a-custom-service-to-activestorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!