Paperclip how to change basename (filename)?

前端 未结 4 2682
粉色の甜心
粉色の甜心 2021-02-20 15:31

I am trying to change the basename (filename) of photos:

In my model I have:

  attr_accessor :image_url, :basename

  has_attached_file :image,
                  


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 15:54

    Paperclip now allows you to pass in a FilenameCleaner object when setting up has_attached_file.

    Your FilenameCleaner object must respond to call with filename as the only parameter. The default FilenameCleaner removes invalid characters if restricted_characters option is supplied when setting up has_attached_file.

    So it'll look something like:

    has_attached_file :image,
                      filename_cleaner: MyRandomFilenameCleaner.new
                      styles: { thumbnail: '100x100' }
    

    And MyRandomFilenameCleaner will be:

    class MyRandomFilenameCleaner
      def call(filename)
        extension = File.extname(filename).downcase
        "#{Digest::SHA1.hexdigest(filename + Time.current.to_s).slice(0..10)}#{extension}"
      end
    end
    

    You could get away with passing in a class that has a self.call method rather than an object but this conforms to Paperclip's documentation in Attachment.rb.

提交回复
热议问题