Created
May 28, 2009 07:29
-
-
Save kakutani/119162 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'fileutils' | |
require 'action_controller/test_process' | |
module UploadedDataHelper | |
def uploaded_data_of(path, mime_type = :auto) | |
mime_type = detect_mimetype_of(File.basename(path)) if mime_type == :auto | |
use_temppath(path) do |temppath| | |
return ActionController::TestUploadedFile.new(temppath, mime_type) | |
end | |
end | |
def use_temppath(filepath) | |
begin | |
tmppath = File.expand_path(File.basename(filepath), Dir.tmpdir) | |
FileUtils.cp filepath, tmppath | |
result = yield(tmppath) | |
rescue => e | |
RAILS_DEFAULT_LOGGER.error("load error: #{filepath} on '#{e}'") | |
ensure | |
FileUtils.rm_rf tmppath if tmppath && File.exist?(tmppath) | |
end | |
result | |
end | |
def detect_mimetype_of(filename) | |
case (ext = File.extname(filename)) | |
when ".gif" | |
"image/gif" | |
when ".jpg", ".jpeg" | |
"image/jpg" | |
when ".png" | |
"image/png" | |
when ".pdf" | |
"application/pdf" | |
when ".zip" | |
"application/zip" | |
else | |
RAILS_DEFAULT_LOGGER.error("detect mimetype error:'#{ext}' is unknown mimetype.") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment