CarrierWaveでファイル名をランダムにする

June 20, 2021

結論

CarrierWaveのwikiに書いてあった。secure_tokenメソッドをuploaderに追加して、filenameメソッドを下記のように変更したらいいとのこと。

class PhotoUploader < CarrierWave::Uploader::Base
  def filename
    "#{secure_token}.#{file.extension}" if original_filename.present?
  end

  protected
  def secure_token
    var = :"@#{mounted_as}_secure_token"
    model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
  end
end
SecureRandomについて

Rubyのモジュール。安全な方法でランダムな乱数を作ってくれる。uuidは、MACアドレスや時刻などの意味のある情報を含みませんとのこと。

バージョン4のUUID(Universally Unique IDentifier)を生成して返します。 version4のUUIDは全くランダムです(バージョンを除いて)。このUUIDはMA アドレスや時刻などのような意味のある情報を含みません


[module SecureRandom](https://docs.ruby-lang.org/ja/latest/class/SecureRandom.html#S_UUID)
参考

module SecureRandom [https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Create-random-and-unique-filenames-for-all-versioned-files](How to: Create random and unique filenames for all versioned files)


Profile picture