Skip to content

Instantly share code, notes, and snippets.

@kakutani
Created May 28, 2009 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakutani/119162 to your computer and use it in GitHub Desktop.
Save kakutani/119162 to your computer and use it in GitHub Desktop.
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