覆盖Rails Paperclip插件的content_type

Fot*_*ios 6 content-type ruby-on-rails paperclip

我想我有一点鸡蛋和鸡蛋的问题.我想设置通过Paperclip上传的文件的content_type.问题是默认的content_type只基于扩展,但我想将它建立在另一个模块上.

我似乎能够使用before_post_process设置content_type

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
Run Code Online (Sandbox Code Playgroud)

但是......我不能将内容类型基于文件,因为Paperclip直到after_create才写入文件.

并且我似乎无法在保存后使用content_type或使用after_create回调(甚至回到控制器中)

所以我想知道在保存之前我是否可以以某种方式访问​​实际的文件对象(假设没有处理器对原始文件做任何事情),这样我就可以在其上运行file_type命令.或者有一种方法可以在创建对象后修改content_type.

Voy*_*yta 4

也许你可以使用upload.to_file. 它为您提供回形针临时文件 ( Paperclip::Tempfile)。它有path属性,所以你可以使用

self.upload.instance_write(:content_type,file_type(self.upload.to_file.path)
Run Code Online (Sandbox Code Playgroud)

你可以Tempfile使用upload.to_file.to_tempfile