CarrierWave:为多种类型的文件创建1个上传器

时间:2011-09-22 17:48:47

标签: ruby-on-rails ruby carrierwave

我想为多种类型的文件(图片,pdf,视频)创建1个上传器

对于每个content_type将采取不同的行动

如何定义文件的content_type?

例如:

if image?
  version :thumb do
    process :proper_resize    
  end
elsif video?
  version :thumb do
    something
  end
end

1 个答案:

答案 0 :(得分:9)

我遇到了这个,它看起来像是如何解决这个问题的一个例子:https://gist.github.com/995663

当您拨打mount_uploader时,首先会加载上传器,此时if image?elsif video?之类的内容将无效,因为尚未定义要上传的文件。您需要在实例化类时调用方法。

我上面给出的链接是重写process方法,因此它需要一个文件扩展名列表,并且仅当您的文件与其中一个扩展名匹配时进行处理

# create a new "process_extensions" method.  It is like "process", except
# it takes an array of extensions as the first parameter, and registers
# a trampoline method which checks the extension before invocation
def self.process_extensions(*args)
  extensions = args.shift
  args.each do |arg|
    if arg.is_a?(Hash)
      arg.each do |method, args|
        processors.push([:process_trampoline, [extensions, method, args]])
      end
    else
      processors.push([:process_trampoline, [extensions, arg, []]])
    end
  end
end

# our trampoline method which only performs processing if the extension matches
def process_trampoline(extensions, method, args)
  extension = File.extname(original_filename).downcase
  extension = extension[1..-1] if extension[0,1] == '.'
  self.send(method, *args) if extensions.include?(extension)
end

然后,您可以使用它来调用过去的过程

IMAGE_EXTENSIONS = %w(jpg jpeg gif png)
DOCUMENT_EXTENSIONS = %(exe pdf doc docm xls)
def extension_white_list
  IMAGE_EXTENSIONS + DOCUMENT_EXTENSIONS
end

process_extensions IMAGE_EXTENSIONS, :resize_to_fit => [1024, 768]

对于版本,在wavewave wiki上有一个页面,允许您有条件地处理版本,如果您在> 0.5.4。 https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing。您必须将版本代码更改为如下所示:

version :big, :if => :image? do
  process :resize_to_limit => [160, 100]
end

protected
def image?(new_file)
  new_file.content_type.include? 'image'
end