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

I want to run Paperclip for all files in a directory on a server. Basically, I would like to allow FTP users some files on my web server, and then I can manually run the rake task so that Paperclip processes all the files (resizing images, updating the database, etc.).

How can i do this?

+6
ruby ruby-on-rails paperclip
source share
1 answer

I'm not sure if I understood your question - are you asking for a remote rake task or how to import images?

In a later case, there is an answer.

First you need a model to save the images and possibly some other data, for example:

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

You can create a simple rake task in the lib / tasks folder (you must specify a file with the extension .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 

Then you can call the manual rake task from the console by providing the SOURCE_DIR parameter, which will be the folder on the server (this can be a real folder or a remote control)

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

If you plan to run it automatically, I recommend that you go to the Resque Scheduler stone.

Update: to keep things simple, I deliberately skipped exception handling

+9
source share

All Articles