新手问题 carrierwave uploader 的 if 条件判断的写法「解决」

brucebot · 2016年03月18日 · 最后由 brucebot 回复于 2016年03月18日 · 2370 次阅读

使用以下的方法测试成功了。

version :thumb, :if => :thumbable? do
   process :efficient_conversion => [640, 960], :if => :pdf?
   process thumbnail: [{format: 'png', quality: 7, size:112, strip: false, square:false, logger: Rails.logger}], :if => :video?
      def full_filename for_file
        png_name for_file, version_name
      end
 end

 version :large, :if => :thumbable? do
   process :efficient_conversion => [640, 960], :if => :pdf?
   process thumbnail: [{format: 'png', quality: 7, size:800, strip: false, square:false, logger: Rails.logger}], :if => :video?
   def full_filename for_file
     png_name for_file, version_name
   end
 end

 def thumbable?(file)
   pdf?(file) || video?(file)
 end

protected
    def video?(new_file)
      new_file.content_type.end_with? '/mp4'
    end

    def pdf?(new_file)
      new_file.content_type.end_with? '/pdf'
    end

==== 在 carriwave 的 uploader 里面针对不同的文件类型,调用不同的截图方法,这个 if 应该怎么写啊?

按照下面这种方法写的话,如果输入的是 pdf 的话,不会执行,本地测试截图不成功。

能帮忙解释一下,version :thumb, :if => :video?这样的语法的全部意思吗?或者类似正常的 ruby 写法。

谢谢。

version :thumb, :if => :video? do
  process thumbnail: [{format: 'png', quality: 7, size:112, strip: false, square:false, logger: Rails.logger}]
  def full_filename for_file
    png_name for_file, version_name
  end
end
version :large, :if => :video? do
  process thumbnail: [{format: 'png', quality: 7, size:800, strip: false, square:false, logger: Rails.logger}]
  def full_filename for_file
    png_name for_file, version_name
  end
end
version :thumb, :if => :pdf? do
  process :efficient_conversion => [640, 960]
  def full_filename for_file
    png_name for_file, version_name
  end
end
version :large, :if => :pdf? do
  process :efficient_conversion => [640, 960]
  def full_filename for_file
    png_name for_file, version_name
  end
end

2 楼 已删除

#1 楼 @watraludru 谢谢,早已看过,搞不定,目前再回去看看 ruby cookbook。

#3 楼 @brucebot

凭直觉,这里的 :if 用法应该类似与 Rails 中 validate 中的 :if 用法。 简单来说,version 是个类实例方法,它的第一个参数是名字,第二个参数是哈希(其中允许使用 :if 作为 Key,其对应的 Value 为 Lambda 对象,或是 Proc 对象,或是当前类/第三个参数中定义的方法(这里内部实现貌似采用的是继承方式)),第三个参数是代码块,其会被包裹在 class_exec 中执行。

你的描述没有说明具体问题,直接问这段代码,让人抓不住要点。因为偶没有用过这个程序库,猜测下原因可能是:

  • 第一参数名字相同时,第二个参数会被合并,第三个参数会在同一作用域/子类作用域中计算。建议改成 pdf_thumb 或是删除 video 相关的所有代码后,进行问题定位
  • 这个插件不支持 PDF,或者需要特殊设置

具体自己看下代码吧:uploader/versions.rb

#4 楼 @watraludru 非常感谢,晚上回去研究下

需要 登录 后方可回复, 如果你还没有账号请 注册新账号