LoginSignup
0
0

More than 5 years have passed since last update.

Paperclipのファイル名変換の仕様について

Posted at

Paperclipでファイルをアップロードした際に、特定の記号がファイル名に含まれていると自動的に「_(アンダースコア)」に変換されます。

[sample]ドキュメント.pdf => _sample_ドキュメント.pdf

数年前のStackOverflowにこのような記事がありました。
Does Paperclip automatically clean up filenames?

PaperclipはURLフレンドリな形式にするため、ファイル名に

[&$+,/:;=?@<>[]{}\|\\^~%# ]

の記号が含まれた場合にデフォルトでアンダースコアに変換する処理が実装されているようです。

https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/attachment.rb#L601

filename_cleanerの中身はこうなっていました。
(invalid_character_regexに置き換え対象の記号を含んだRegexpオブジェクトが渡されます)

lib/paperclip/filename_cleaner.rb

module Paperclip
  class FilenameCleaner
    def initialize(invalid_character_regex)
      @invalid_character_regex = invalid_character_regex
    end

    def call(filename)
      if @invalid_character_regex
        filename.gsub(@invalid_character_regex, "_")
      else
        filename
      end
    end
  end
end

単純に指定した記号がファイル名に含まれている場合は全てアンダースコアに変換するようです。
この挙動については、"restricted_characters"というオプションを渡すことで変更可能です。

has_attached_file :attachment,
  restricted_characters: nil
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0