Class: Paperclip::ContentTypeDetector

Inherits:
Object
  • Object
show all
Defined in:
lib/paperclip/content_type_detector.rb

Overview

The content-type detection strategy is as follows:

  1. Blank/Empty files: If there's no filepath or the file is empty, provide a sensible default (application/octet-stream or inode/x-empty)

  2. Calculated match: Return the first result that is found by both the Marcel gem (or file command) and MIME::Types.

  3. Standard types: Return the first standard (without an x- prefix) entry in MIME::Types

  4. Experimental types: If there were no standard types in MIME::Types list, try to return the first experimental one

  5. Raw file command: Just use the output of Marcel (or file command), cached from step 2.

  6. If nothing found, return a sensible default.

Constant Summary collapse

EMPTY_TYPE =
"inode/x-empty"
SENSIBLE_DEFAULT =
"application/octet-stream"

Instance Method Summary collapse

Constructor Details

#initialize(filepath) ⇒ ContentTypeDetector

Returns a new instance of ContentTypeDetector.



26
27
28
# File 'lib/paperclip/content_type_detector.rb', line 26

def initialize(filepath)
  @filepath = filepath
end

Instance Method Details

#detect(default = SENSIBLE_DEFAULT) ⇒ Object

Returns a String describing the file's content type



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/paperclip/content_type_detector.rb', line 31

def detect(default = SENSIBLE_DEFAULT)
  if blank_name?
    default
  elsif empty_file?
    EMPTY_TYPE
  elsif calculated_type_matches.any?
    calculated_type_matches.first
  else
    type_from_file_contents || default
  end.to_s
end