我想我有点鸡和蛋的问题。我想设置通过回形针上传的文件的内容类型。问题是,默认的内容类型仅基于扩展,但我希望它基于另一个模块。
我似乎能用“前-后”过程设置内容类型
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
但是…我不能基于文件的内容类型,因为剪纸在创建后才写入文件。
我似乎无法在内容保存后或使用后创建回调(甚至在控制器中)设置内容类型。
所以我想知道在保存文件之前是否可以访问实际的文件对象(假设没有处理器对原始文件做任何操作),这样我就可以对其运行file_type命令。或者,是否有方法在创建对象后修改内容类型?