Module: CarrierWave::Magic

Extended by:
ActiveSupport::Concern
Defined in:
lib/carrierwave-magic.rb,
lib/carrierwave-magic/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#set_magic_content_type(override = false) ⇒ Object

Changes the file content_type using the ruby-filemagic gem



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/carrierwave-magic.rb', line 33

def set_magic_content_type(override=false)
  if override || file.content_type.blank? || generic_content_type?(file.content_type)
    new_content_type = ::FileMagic.new(::FileMagic::MAGIC_MIME).file( file.path ).split(';').first

    if file.respond_to?(:content_type=)
      file.content_type = new_content_type
    else
      file.instance_variable_set(:@content_type, new_content_type)
    end

    unless MIME::Types[new_content_type].first.nil?
      if file.respond_to?(:extension=)
        file.extension = MIME::Types[new_content_type].first.extensions.first
      else
        file.instance_variable_set(:@extension, MIME::Types[new_content_type].first.extensions.first)
      end
    end
  end
rescue ::Exception => e
  raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.magic_mime_types_processing_error", e: e, default: 'Failed to process file with FileMagic, Original Error: %{e}')
end