Techioz Blog

ストレージと対話するときにフォグプロバイダーを動的に選択するにはどうすればよいですか?

概要

画像を含む単純な Rails モデルがあります。現在、イメージは 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 を動的に変更する必要があることです。どうすればこれを達成できますか? 1 つのアップローダー内から実行できますか、それとも別のアップローダー クラスが必要ですか。その場合、バックエンド属性に基づいて CarImage モデルに使用するクラスを選択するにはどうすればよいですか?

よろしく

解決策

モデルのバックエンドを確認し、資格情報を適切に設定できます。

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