Commit 5be67595 by Alex Godin

working implementation of the mime-types gem

parent 1ff1cc73
......@@ -10,3 +10,4 @@ gem "appraisal"
gem "fog"
gem "bundler"
gem "cocaine"
gem "mime-types"
......@@ -69,6 +69,7 @@ DEPENDENCIES
bundler
cocaine
fog
mime-types
mocha
rake
shoulda
......
......@@ -6,24 +6,28 @@ module Paperclip
# 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)
......
......@@ -8,6 +8,7 @@ require 'mocha'
require 'active_record'
require 'active_record/version'
require 'active_support'
require 'mime/types'
puts "Testing against version #{ActiveRecord::VERSION::STRING}"
......
......@@ -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|
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment