Overriding content_type for the Rails Sperclip plugin

I think I have a problem with chicken and egg. I would like to set the content_type of the file downloaded through Paperclip. The problem is that the default value of content_type is based only on the extension, but I would like to base it on another module.

It seems I can set content_type with parameter 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 does not write the file until after_create.

And I cannot set the content_type after it has been saved or with the after_create callback (even back to the controller)

So, I would like to know if I can somehow access the actual file object (suppose the processors do nothing with the source file) before saving it, so I can run the file_type command. Or is there a way to change the content_type after creating the objects.

+6
content-type ruby-on-rails paperclip
source share
1 answer

Perhaps you can use upload.to_file . It provides a temporary paperclip file ( Paperclip::Tempfile ). It has a path property, so you can use

 self.upload.instance_write(:content_type,file_type(self.upload.to_file.path) 

You can get Tempfile with upload.to_file.to_tempfile

+4
source share

All Articles