Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Jan 07

Simulate a multipart-post request in a rake task

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

Hi, I’ve found how to simulate a multipart-post request and execute it in a rake task. A possible scenario where you need this kind of script could be the necessity to pre-fill a gallery. In this case a smart solution can be call the ‘create’ action for each image you want to insert in order to allow the creation of thumbnails without duplicate your ‘create’ code in the rake task.

To do this, you first need to apply a patch to fix an annoying problems related to the fact that MockCGI object marshals all of the inputs into a StringIO.

Then you can create your rake task using multipart_post instead of post; here is an example:


namespace :imgs do

  desc "load all the images of a given path and stores them in a given table" 
  task :load => :environment do

    require RAILS_ROOT+"/vendor/rails/actionpack/lib/action_controller/integration.rb" 

    img_path = ENV['IMGPATH']
    target_model = ENV['TARGETMODEL']

    imgs = Dir.glob(img_path+"*.jpg")

    post_session = ActionController::Integration::Session.new()

    imgs.each do |img|

      puts "Chiamo il post per #{img}" 
      post_session.multipart_post --HERE YOUR CREATE ACTION PATH--, target_model.to_sym => { 
                                                                    :uploaded_data => ActionController::TestUploadedFile.new(img,'image/jpeg'),
                                                                    :title => File.basename(img,'.jpg')
                                                                  }

      puts "Sleep (10sec)" 
      sleep 10

    end

  end


Comments

  • ni

    Posted on January 25

    good post

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory