Sunday, March 20, 2011

File uploads in import scripts


Simulating file uploads in your scripts or from console can be done really simple using Rail’s ActionController::TestUploadedFile fromaction_pack.
Example code:
require 'action_controller/test_process'
 
class ImportExternalData
...
def import_data
...
page.attachments << PageAttachment.new(
:uploaded_data => fake_file_upload(filename, mime_type),
:title => title,
:description => description)
...
end
 
 
protected
def fake_file_upload(path, mime_type = nil, binary = false)
ActionController::TestUploadedFile.new(
path,
mime_type,
binary
)
end
end
Excerpt from ActionController::TestUploadedFile’s comments:
Essentially generates a modified Tempfile object similar to the object
you’d get from the standard library CGI module in a multipart
request. This means you can use an ActionController::TestUploadedFile
object in the params of a test request in order to simulate
a file upload.

No comments:

Post a Comment