ruby 如何在与存储交互时动态选择雾提供程序?

s5a0g9ez  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(95)

我有一个简单的rails模型,其中包含一个image。这些图像目前存储在AWS S3中,但我需要将它们移动到Backblaze。我有一个上传类,看起来也是这样的:

class CarImage < ApplicationRecord
  VALID_BACKENDS = [:s3, :backblaze].freeze
  enum backend: VALID_BACKENDS
  mount_uploader :image, CarImageUploader

  belongs_to :car
end

class CarImageUploader < CarrierWave::Uploader::Base
  configure do |config|
    config.fog_credentials = {
      provider: "AWS",
      aws_access_key_id: Rails.application.credentials.aws_access_key_id,
      aws_secret_access_key: Rails.application.credentials.aws_secret_access_key,
      region: Rails.application.credentials.aws_region
    }
    config.fog_directory  = Rails.application.credentials.aws_image_bucket
    config.fog_public     = true
    config.fog_attributes = { "Cache-Control" => "max-age=315576000" }
    config.remove_previously_stored_files_after_update = false
  end

  def store_dir
    "uploads/car_images/#{model.car_id}"
  end
end

字符串
现在我的问题是,我需要根据model.backend动态更改config.fog_credentials。我如何才能做到这一点?我可以从一个上传器中完成它吗?或者我需要不同的上传器类-如果是这样,我如何根据backend属性选择哪一个应该用于CarImage模型?
谨致问候

jgzswidk

jgzswidk1#

您可以检查model的后端并适当设置凭据:

class CarImage < ApplicationRecord
  VALID_BACKENDS = [:s3, :backblaze].freeze
  enum backend: VALID_BACKENDS
  mount_uploader :image, CarImageUploader

  belongs_to :car
end

class CarImageUploader < CarrierWave::Uploader::Base
  configure do |config|
    config.fog_public     = true
    config.fog_attributes = { "Cache-Control" => "max-age=315576000" }
    config.remove_previously_stored_files_after_update = false
  end

  def fog_credentials
    model.s3? ? s3_fog_credentials : backblaze_fog_credentials
  end

  def fog_directory 
    model.s3? ? Rails.application.credentials.aws_image_bucket : Rails.application.credentials.backblaze_image_bucket
  end

  def store_dir
    "uploads/car_images/#{model.car_id}"
  end

  private

  def s3_fog_credentials
    {
      provider: "AWS",
      aws_access_key_id: Rails.application.credentials.aws_access_key_id,
      aws_secret_access_key: Rails.application.credentials.aws_secret_access_key,
      region: Rails.application.credentials.aws_region
    }
  end

  def backblaze_fog_credentials
    # your backblaze go here
  end
end

字符串

相关问题