Module: MagicPaperclip

Defined in:
lib/magic-paperclip.rb,
lib/magic-paperclip/railtie.rb,
lib/magic-paperclip/version.rb

Defined Under Namespace

Classes: Railtie

Constant Summary collapse

VERSION =
"0.0.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



16
17
18
19
20
21
# File 'lib/magic-paperclip.rb', line 16

def self.included( base )
  base.class_eval do
    alias_method :assign_without_filemagic, :assign
    alias_method :assign, :assign_with_filemagic
  end
end

Instance Method Details

#assign_with_filemagic(uploaded_file) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/magic-paperclip.rb', line 23

def assign_with_filemagic( uploaded_file )
  # Call next method up the chain
  val = assign_without_filemagic( uploaded_file )

  return val if uploaded_file.is_a?( Paperclip::Attachment )

  if uploaded_file
    magic = FileMagic.new( FileMagic::MAGIC_MIME )

    if defined?( StringIO ) && uploaded_file.is_a?( StringIO )
      type = magic.buffer( uploaded_file.string )
    else
      type = magic.file( uploaded_file.path )
    end

    # Remove the '; charset=us-ascii' from the end if there is one
    type.sub! /\s*;.*$/, ''

    instance_write( :content_type, type )
  end
  val
ensure
  magic.close if magic
end