Skip to content

Instantly share code, notes, and snippets.

@pataiji
Created November 28, 2013 12:16
Show Gist options
  • Save pataiji/7690979 to your computer and use it in GitHub Desktop.
Save pataiji/7690979 to your computer and use it in GitHub Desktop.
Paperclipのアタッチメントを保存する前にリネームします。
# coding: utf-8
#
# 使用したいモデルでインクルード
# ex) include FileRenamer
module FileRenamer
extend ActiveSupport::Concern
module ClassMethods
# paperclipのattachmentのファイルをリネームする
#
# リネームしたいカラムを指定します
# ex) attr_file_renamer :image_1 [, :image_2, :image_3]
def attr_file_renamer(*names)
names.each do |name|
define_method("rename_file_#{name}") do
file = self.instance_eval(name.to_s)
if file.queued_for_write.present?
extname = File.extname(file.queued_for_write[:original].path)
basename = File.basename(file.queued_for_write[:original].path, extname)
file_name = "#{Digest::MD5.hexdigest(basename + Time.now.to_i.to_s)}#{extname}"
file.instance_write(:file_name, file_name)
end
end
self.send('before_save', :"rename_file_#{name}")
end
end
end
end
class Image < ActiveRecord::Base
include FileRenamer
attr_file_renamer :image_1, :image_2, :image_3, :image_4, :image_5
has_attached_file :image_1
has_attached_file :image_2
has_attached_file :image_3
has_attached_file :image_4
has_attached_file :image_5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment