class Paperclip::ContentTypeDetector

Constants

EMPTY_TYPE
SENSIBLE_DEFAULT

Public Class Methods

new(filename) click to toggle source
# File lib/paperclip/content_type_detector.rb, line 6
def initialize(filename)
  @filename = filename
end

Public Instance Methods

detect() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 10
def detect
  if blank?
    SENSIBLE_DEFAULT
  elsif empty?
    EMPTY_TYPE
  elsif !match?
    type_from_file_command
  elsif !multiple?
    possible_types.first
  else
    best_type_match
  end.to_s
end

Private Instance Methods

best_type_match() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 46
def best_type_match
  official_types = possible_types.reject {|type| type.content_type.match(/\/x-/) }
  (official_types.first || possible_types.first).content_type
end
blank?() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 30
def blank?
  @filename.nil? || @filename.empty?
end
empty?() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 26
def empty?
  File.exists?(@filename) && File.size(@filename) == 0
end
match?() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 38
def match?
  possible_types.length > 0
end
multiple?() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 42
def multiple?
  possible_types.length > 1
end
possible_types() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 34
def possible_types
  @possible_types ||= MIME::Types.type_for(@filename)
end
type_from_file_command() click to toggle source
# File lib/paperclip/content_type_detector.rb, line 51
def type_from_file_command
  type = begin
    # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
    Paperclip.run("file", "-b --mime :file", :file => @filename)
  rescue Cocaine::CommandLineError => e
    Paperclip.log("Error while determining content type: #{e}")
    SENSIBLE_DEFAULT
  end

  if type.match(/\(.*?\)/)
    type = SENSIBLE_DEFAULT
  end
  type.split(/[:;\s]+/)[0]
end