2010-09-27 42 views
6

我想在服务器上的目录中的所有文件上运行Paperclip。基本上,我想允许用户FTP一些文件到我的网络服务器,然后我可以手动运行一个耙子任务让Paperclip处理所有文件(调整图像大小,更新数据库等)。如何从服务器目录制作Paperclip流程文件?

我该怎么做?

+0

我太需要这个从旧系统中的文件在磁盘上的Rails环境静态转换。基本上只需打开文件并将其分配给目标模型'has_attached_file'属性并保存。 – Chloe 2014-05-09 19:57:48

回答

9

我不知道我是否理解你的问题 - 你是要求远程运行rake任务还是如何导入图像?

在后面的情况下有答案。

首先,你需要一些模型,以保持图像和也许一些其他的数据,这样的事情:

class Picture < ActiveRecord::Base 
    has_attached_file :image, :styles => { 
     :thumb => "100x100>", 
     :big => "500x500>" 
     } 
end 

您可以创建在你的lib/tasks文件夹简单的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 

然后你可以手动调用从控制台提供SOURCE_DIR参数,这将是服务器上的文件夹耙任务(也可以是真正的文件夹或安装远程)

rake import:images SOURCE_DIR=~/my_images/to/be/imported 

如果你打算自动运行这个,我建议你去使用Resque Scheduler gem。

更新:为了简单起见,我特意省略异常处理

+0

这真棒,我认为这正是我需要的。我会在今天晚些时候尝试。 – NotDan 2010-09-27 14:38:39

+0

很高兴听到它! – 2010-09-27 14:45:51

+0

超级简单,谢谢! – NotDan 2010-09-27 17:52:07

相关问题