ActiveStorage & S3: Make files public

限于喜欢 提交于 2021-02-07 10:33:22

问题


In my rails application, some images should be public and others should be private. (I don't mind to have all of them public).

Currently, when calling ActiveStorage's service_url (when using s3), a new presigned url is being generated. I totally understand this, but it's not what I want to do.

Right now, generating the presigned url is taking too much time:


Example:

Getting 10 records:

  • ActiveRecord: 52.3ms
  • Generating the JSON: 1,790ms

If we dig deeper, we see the following:

  • S3 Storage (23.9ms) Checked if file exists at key: variants/p5Enur12ZMUEgMb6niJDtS2W/6cb99d2f2eca3bafc444d3c7cdfab34cd303f2578891852655d60028981c8950 (yes)
  • S3 Storage (3.2ms) Generated URL for file at key: variants/p5Enur12ZMUEgMb6niJDtS2W/6cb99d2f2eca3bafc444d3c7cdfab34cd303f2578891852655d60028981c8950

In my example, I'm getting 10 Matches, where each Match has teams and competition. Team and Competition have one image.

I'm also generating the following JSON Structure:

{
  ...
  image: {
    original: ...,
    thumbnail: ...,
    medium: ...,
    large: ...,
  }
}

With this taken into consideration, here are the numbers:

  • 10 matches * ( 1 team + 1 competition ) = 20 images
  • each image has 4 sizes
  • each size takes around 27ms
  • --> 20 * 4 * 27 = ~2,160ms

Is there a way to make all the uploaded files public and we'll have the 2,160ms completely removed ?

---

Edit: answer

def url_for_file(file:, size: nil, process: false)
  s3_storage = Rails.application.config.active_storage.service == :amazon

  if size.nil?
    url = file
  else
    url = file.variant(size)

    if process
      url = url.processed
    end
  end

  if s3_storage
    amazon_config = Rails.application.config.active_storage.service_configurations.amazon
    return "https://s3.#{amazon_config.region}.amazonaws.com/#{amazon_config.bucket}/#{url.key}"
  else
    return url.service_url
  end
end

With this small hack, you will only process the files when you want ( and assume they are processed when presenting ), also, won't call .service_url which checks if the file exists. This is only valid if your acl config is public.

来源:https://stackoverflow.com/questions/57946351/activestorage-s3-make-files-public

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