【问题标题】:Paperclip image dimensions custom validator回形针图像尺寸自定义验证器
【发布时间】:2012-09-12 13:06:42
【问题描述】:

这是我的图像模型,我在其中实现了一个验证附件尺寸的方法:

class Image < ActiveRecord::Base
  attr_accessible :file

  belongs_to :imageable, polymorphic: true

  has_attached_file :file,
                     styles: { thumb: '220x175#', thumb_big: '460x311#' }

  validates_attachment :file,
                        presence: true,
                        size: { in: 0..600.kilobytes },
                        content_type: { content_type: 'image/jpeg' }

  validate :file_dimensions

  private

  def file_dimensions(width = 680, height = 540)
    dimensions = Paperclip::Geometry.from_file(file.queued_for_write[:original].path)
    unless dimensions.width == width && dimensions.height == height
      errors.add :file, "Width must be #{width}px and height must be #{height}px"
    end
  end
end

这很好用,但它不可重复使用,因为该方法采用固定的宽度和高度值。我想将其转换为自定义验证器,因此我也可以在其他模型中使用它。我已经阅读了有关此的指南,我知道 app/models/dimensions_validator.rb 中会是这样的:

class DimensionsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    dimensions = Paperclip::Geometry.from_file(record.queued_for_write[:original].path)

    unless dimensions.width == 680 && dimensions.height == 540
      record.errors[attribute] << "Width must be #{width}px and height must be #{height}px"
    end
  end
end

但我知道我遗漏了一些东西,因为此代码不起作用。问题是我想在我的模型中调用这样的验证:

validates :attachment, dimensions: { width: 300, height: 200}.

知道如何实现这个验证器吗?

【问题讨论】:

  • 我不确定,但我认为您可以通过 options 属性访问您的宽度和高度。例如:options[:width]options[:height]

标签: ruby-on-rails ruby-on-rails-3 paperclip paperclip-validation


【解决方案1】:

把这个放在 app/validators/dimensions_validator.rb:

class DimensionsValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    # I'm not sure about this:
    dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path)
    # But this is what you need to know:
    width = options[:width]
    height = options[:height] 

    record.errors[attribute] << "Width must be #{width}px" unless dimensions.width == width
    record.errors[attribute] << "Height must be #{height}px" unless dimensions.height == height
  end
end

那么,在模型中:

validates :file, :dimensions => { :width => 300, :height => 300 }

【讨论】:

  • 我们不必将验证器添加到 load_path 中,只要将文件放在 models/ 中并按照 Rails 约定 (dimensions_validator.rb) 命名即可。我已经编辑了答案。谢谢!
  • 太棒了。我们如何仅在上传图像时执行检查?我尝试了一些“除非record.nil?”和'除非 value.nil?'但它没有用。
  • 你可以试试:if value.present?,但我认为value.nil? 应该可以工作。value 没有上传,你调试它的值是多少?
  • 我建议不要将其放入/app/models。将文件放在/app/validators 中仍然会导致 Rails 自动加载文件,并且会按照 SRP 保持模型目录干净。
  • 为什么不把它添加为宝石呢?我会创建一个
【解决方案2】:

有一个叫做 paperclip-dimension-validator 的 gem。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多