2011-09-22 22 views

回答

9

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

当您拨打mount_uploader时,上传器首先被加载,此时诸如if image?或之类的东西将不起作用,因为尚未定义上传文件。您需要在实例化类时调用方法。

什么我给上面呢,是重写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] 

适用版本,有一个在carrierwave维基,使您可以有条件地处理的版本,如果你在> 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 
+0

我能尝试一下......我会更新我的答案 – keithepley

+0

另一个更新......想通了如何利用选择性照顾创建版本 – keithepley

+0

太棒了!谢谢! – manzhikov

相关问题