Permalink
Browse files

working implementation of the mime-types gem

  • Loading branch information...
1 parent 1ff1cc7 commit 5be67595d7fc0ef768685be632aead0022a41e1f @alexgodin alexgodin committed Jun 29, 2011
Showing with 23 additions and 16 deletions.
  1. +1 −0 Gemfile
  2. +1 −0 Gemfile.lock
  3. +18 −14 lib/paperclip/upfile.rb
  4. +1 −0 test/helper.rb
  5. +2 −2 test/upfile_test.rb
View
@@ -10,3 +10,4 @@ gem "appraisal"
gem "fog"
gem "bundler"
gem "cocaine"
+gem "mime-types"
View
@@ -69,6 +69,7 @@ DEPENDENCIES
bundler
cocaine
fog
+ mime-types
mocha
rake
shoulda
@@ -6,24 +6,28 @@ module Upfile
# Infer the MIME-type of the file from the extension.
def content_type
- type = (self.original_filename.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
- case type
- when %r"jp(e|g|eg)" then "image/jpeg"
- when %r"tiff?" then "image/tiff"
- when %r"png", "gif", "bmp" then "image/#{type}"
- when %r"svg" then "image/svg+xml"
- when "txt" then "text/plain"
- when %r"html?" then "text/html"
- when "js" then "application/js"
- when "csv", "xml", "css" then "text/#{type}"
+ types = MIME::Types.type_for(self.original_filename)
+ if types.length == 0
+ type_from_file_command
+ elsif types.length == 1
+ types.first.content_type
else
- # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
- content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}")
- content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/)
- content_type
+ iterate_over_array_to_find_best_option(types)
end
end
+ def iterate_over_array_to_find_best_option(types)
+ types.reject {|type| type.content_type.match(/\/x-/) }.first
+ end
+
+ def type_from_file_command
+ # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
+ type = (self.original_filename.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
+ mime_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}")
+ mime_type = "application/x-#{type}" if mime_type.match(/\(.*?\)/)
+ mime_type
+ end
+
# Returns the file's normal name.
def original_filename
File.basename(self.path)
View
@@ -8,6 +8,7 @@
require 'active_record'
require 'active_record/version'
require 'active_support'
+require 'mime/types'
puts "Testing against version #{ActiveRecord::VERSION::STRING}"
View
@@ -10,9 +10,9 @@ class UpfileTest < Test::Unit::TestCase
%w(txt) => 'text/plain',
%w(htm html) => 'text/html',
%w(csv) => 'text/csv',
- %w(xml) => 'text/xml',
+ %w(xml) => 'application/xml',
%w(css) => 'text/css',
- %w(js) => 'application/js',
+ %w(js) => 'application/javascript',
%w(foo) => 'application/x-foo'
}.each do |extensions, content_type|
extensions.each do |extension|

0 comments on commit 5be6759

Please sign in to comment.