Overriding content_type for Rails Paperclip plugin
Posted
by Fotios
on Stack Overflow
See other posts from Stack Overflow
or by Fotios
Published on 2010-04-05T21:01:10Z
Indexed on
2010/04/05
21:03 UTC
Read the original article
Hit count: 268
I think I have a bit of a chicken and egg problem. I would like to set the content_type of a file uploaded via Paperclip. The problem is that the default content_type is only based on extension, but I'd like to base it on another module.
I seem to be able to set the content_type with the before_post_process
class Upload < ActiveRecord::Base
has_attached_file :upload
before_post_process :foo
def foo
logger.debug "Changing content_type"
#This works
self.upload.instance_write(:content_type,"foobar")
# This fails because the file does not actually exist yet
self.upload.instance_write(:content_type,file_type(self.upload.path)
end
# Returns the filetype based on file command (assume it works)
def file_type(path)
return `file -ib '#{path}'`.split(/;/)[0]
end
end
But...I cannot base the content type on the file because Paperclip doesn't write the file until after_create.
And I cannot seem to set the content_type after it has been saved or with the after_create callback (even back in the controller)
So I would like to know if I can somehow get access to the actual file object (assume there are no processors doing anything to the original file) before it is saved, so that I can run the file_type command on that. Or is there a way to modify the content_type after the objects have been created.
© Stack Overflow or respective owner