gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:39:49 24 4
gpt4 key购买 nike

这是我的 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

但我知道我错过了一些东西,因为这段代码不起作用。问题是我想在我的模型中像这样调用验证:
validates :attachment, dimensions: { width: 300, height: 200} .

关于应该如何实现这个验证器的任何想法?

最佳答案

把它放在 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 }

关于ruby-on-rails - 回形针图像尺寸自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12388887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com