class Paperclip::ContentTypeDetector
Constants
- EMPTY_TYPE
The content-type detection strategy is as follows:
-
Blank/Empty files: If there's no filepath or the file is empty, provide a sensible default (application/octet-stream or inode/x-empty)
-
Calculated match: Return the first result that is found by both the `file` command and MIME::Types.
-
Standard types: Return the first standard (without an x- prefix) entry in MIME::Types
-
Experimental types: If there were no standard types in MIME::Types list, try to return the first experimental one
-
Raw `file` command: Just use the output of the `file` command raw, or a sensible default. This is cached from Step 2.
-
- SENSIBLE_DEFAULT
Public Class Methods
new(filepath)
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 23 def initialize(filepath) @filepath = filepath end
Public Instance Methods
detect()
click to toggle source
Returns a String describing the file's content type
# File lib/paperclip/content_type_detector.rb, line 28 def detect if blank_name? SENSIBLE_DEFAULT elsif empty_file? EMPTY_TYPE elsif calculated_type_matches.any? calculated_type_matches.first else type_from_file_contents || SENSIBLE_DEFAULT end.to_s end
Private Instance Methods
blank_name?()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 42 def blank_name? @filepath.nil? || @filepath.empty? end
calculated_type_matches()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 52 def calculated_type_matches possible_types.select do |content_type| content_type == type_from_file_contents end end
empty_file?()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 46 def empty_file? File.exist?(@filepath) && File.size(@filepath) == 0 end
Also aliased as: empty?
possible_types()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 58 def possible_types MIME::Types.type_for(@filepath).collect(&:content_type) end
type_from_file_command()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 75 def type_from_file_command @type_from_file_command ||= FileCommandContentTypeDetector.new(@filepath).detect end
type_from_file_contents()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 62 def type_from_file_contents type_from_mime_magic || type_from_file_command rescue Errno::ENOENT => e Paperclip.log("Error while determining content type: #{e}") SENSIBLE_DEFAULT end
type_from_mime_magic()
click to toggle source
# File lib/paperclip/content_type_detector.rb, line 69 def type_from_mime_magic @type_from_mime_magic ||= File.open(@filepath) do |file| MimeMagic.by_magic(file).try(:type) end end