ruby-on-rails – 回形针图像尺寸自定义验证器

这是我的 Image模型,我在其中实现了一种验证附件尺寸的方法
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

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

验证:附件,尺寸:{宽度:300,高度:200}.

有关如何实施此验证器的任何想法?

解决方法

把它放在app / validators / dimensions_validator.rb中:
class DimensionsValidator < ActiveModel::EachValidator
  def validate_each(record,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 }

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...