How to rename a file with file_column plugin.
Собственно, понадобилось… Время от времени изменять имя файла, загруженного с помощью file_column. Например так: stylesheet.css → stylesheet_1399194798.css.
Вот, что получилось.
Модель
/app/models/custom_template_file.rb
class CustomTemplateFile < ActiveRecord::Base
db_magic_init
#... blah-blah...
belongs_to :fileable, :polymorphic => true
file_column :file, :fix_file_extensions => false
#...
# Renames the file and saves a file-data into db field
def rename_to(new_name)
file_dir = File.dirname(file)
file_path = "#{dirname}/#{new_name}"
File.rename(file, file_path)
# Update db field
update_attributes( :file => f = File.open(file_path, "r") )
f.close
end
#...
end
Контроллер
И использую созданный метод rename_to, например, в контроллере.
/app/controllers/template_controller.rb
#...
# Returns a CustomTemplateFile obj :file => "stylesheet.css"
@template_file = @template.custom_template_file(:stylesheet)
#...
# Renames the file using timestamp
@template_file.rename_to("stylesheet_#{Time.now.to_i}.css")
#...
Копипастить необязательно; импровизируй! :)
Тут и сказочке #EOF



0 Комментариев :
Отправить комментарий
Жги!