开发者

How can I make Paperclip process files from a server directory?

I want to run Paperclip on all files in a directory on the server. Basically, I would like to allow users to FTP some files to my webserver, then I can manually run a rake task to have Paperclip process all of the开发者_如何学运维 files (resize the images, update the database, etc).

How can I do this?


I'm not sure if I understood your question - are you asking to run the rake task remotely or how to import images?

In the later case there is an answer.

First you need some Model to keep the images and maybe some other data, something like this:

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

You can create simple rake task in your lib/tasks folder (you should name the file with .rake extension)

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

Then you can call manually rake task from the console providing SOURCE_DIR parameter that will be the folder on the server (it can be real folder or mounted remote)

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

If you are planning to run this automatically I'd recommend you to go for Resque Scheduler gem.

Update: To keep things simple I've deliberately omitted exception handling

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜