Skip to content

Instantly share code, notes, and snippets.

@joshmcarthur
Last active May 20, 2020 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshmcarthur/e30f74268fbddbfae0db563eb1b2fa74 to your computer and use it in GitHub Desktop.
Save joshmcarthur/e30f74268fbddbfae0db563eb1b2fa74 to your computer and use it in GitHub Desktop.
Patch CarrierWave to test file content type using UNIX's 'file' utility
# lib/carrierwave_ext/sanitized_file.rb
require "carrierwave/sanitized_file"
module CarrierWave
class SanitizedFile
##
# Returns the content type of the file.
#
# === Returns
#
# [String] the content type of the file
#
def content_type
@content_type ||=
existing_content_type ||
file_utility_content_type ||
mime_magic_content_type ||
mini_mime_content_type
end
##
# Uses the UNIX 'file' utility to extract the content type from
# the file path.
#
# === Returns
#
# [String] the content type of the file, or nil if the 'file' command is not found or fails
# to resolve a mimetype
def file_utility_content_type
return unless path
return if system("which file", out: File::NULL).blank?
# An invalid path echos a warning to STDERR
`file --brief --keep-going --mime-type #{path.shellescape}`
.strip
.downcase
.presence
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment