Use Paperclip in rack app like sinatra and how to write test

Tips,ruby 8 十一月 2011 | View Comments

You’ll find rack parse uploaded file in different format to Rails

Here is the format in rack app.

"image"=>{:type=>"image/jpeg", :filename=>"listing[image]", :tempfile=>#<File:/tmp/RackMultipart20111107-16008-erra0z-0>, :head=>"Content-Disposition: form-data; name=\"listing[image]\"; filename=\"listing[image]\"\r\nContent-Type: image/jpeg\r\n", :name=>"listing[image]"}

You can simply covert it to right format.

post "some_api" do
yourModel = YourModel.new(:image => to_paperclip(params['image']))
yourModel.save
end
def to_paperclip(image)
  paperclip = {}
  paperclip['tempfile'] = image[:tempfile]
  paperclip['filename'] = image[:filename]
  paperclip['content_type'] = image[:type]
  paperclip['size'] = image[:tempfile].size
  paperclip
end

How to test

 filename = Rails.root.join "spec/fixtures/rails.png"
 file = Rack::Test::UploadedFile.new(filename, "image/png")
 post "/api/v1/some_api", {:image => file}
 # should have image uploaded


Tagged in , , ,

Ads Plugin created by Jake Ruston's Wordpress Plugins - Powered by and football database.