我想在服务器上的目录中的所有文件上运行Paperclip.基本上,我想允许用户将一些文件FTP到我的网络服务器,然后我可以手动运行rake任务让Paperclip处理所有文件(调整图像大小,更新数据库等).
我怎样才能做到这一点?
解决方法
我不确定我是否理解你的问题 – 你是要求远程运行rake任务还是如何导入图像?
在后一种情况下,有一个答案.
首先,你需要一些模型来保存图像和其他一些数据,如下所示:
- class Picture < ActiveRecord::Base
- has_attached_file :image,:styles => {
- :thumb => "100x100>",:big => "500x500>"
- }
- end
您可以在lib / tasks文件夹中创建简单的rake任务(您应该使用.rake扩展名命名该文件)
- namespace :import do
- desc "import all images from SOURCE_DIR folder"
- task :images => :environment do
- # get all images from given folder
- Dir.glob(File.join(ENV["SOURCE_DIR"],"*")) do |file_path|
- # create new model for every picture found and save it to db
- open(file_path) do |f|
- pict = Picture.new(:name => File.basename(file_path),:image => f)
- # a side affect of saving is that paperclip transformation will
- # happen
- pict.save!
- end
- # Move processed image somewhere else or just remove it. It is
- # necessary as there is a risk of "double import"
- #FileUtils.mv(file_path,"....")
- #FileUtils.rm(file_path)
- end
- end
- end
然后你可以从控制台手动调用rake任务,提供SOURCE_DIR参数,该参数将是服务器上的文件夹(它可以是真正的文件夹或安装的远程)
- rake import:images SOURCE_DIR=~/my_images/to/be/imported
如果您打算自动运行,我建议您使用Resque Scheduler gem.
更新:为了简单起见,我故意省略了异常处理