Module: Paperclip::Upfile

Included in:
File
Defined in:
lib/paperclip/upfile.rb

Overview

The Upfile module is a convenience module for adding uploaded-file-type methods to the File class. Useful for testing.

user.avatar = File.new("test/test_avatar.jpg")

Instance Method Summary collapse

Instance Method Details

#content_typeObject

Infer the MIME-type of the file from the extension.



10
11
12
13
14
15
16
17
18
19
# File 'lib/paperclip/upfile.rb', line 10

def content_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
    iterate_over_array_to_find_best_option(types)
  end
end

#iterate_over_array_to_find_best_option(types) ⇒ Object



21
22
23
# File 'lib/paperclip/upfile.rb', line 21

def iterate_over_array_to_find_best_option(types)
  types.reject {|type| type.content_type.match(/\/x-/) }.first
end

#original_filenameObject

Returns the file’s normal name.



34
35
36
# File 'lib/paperclip/upfile.rb', line 34

def original_filename
  File.basename(self.path)
end

#sizeObject

Returns the size of the file.



39
40
41
# File 'lib/paperclip/upfile.rb', line 39

def size
  File.size(self)
end

#type_from_file_commandObject



25
26
27
28
29
30
31
# File 'lib/paperclip/upfile.rb', line 25

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 :file", :file => self.path).split(/[:;]\s+/)[0] rescue "application/x-#{type}")
  mime_type = "application/x-#{type}" if mime_type.match(/\(.*?\)/)
  mime_type
end