Last active
May 20, 2020 21:50
-
-
Save joshmcarthur/e30f74268fbddbfae0db563eb1b2fa74 to your computer and use it in GitHub Desktop.
Patch CarrierWave to test file content type using UNIX's 'file' utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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