Rails Paperclip,DRY配置

3
为了简化我的附件图片代码,我创建了一个初始化器来覆盖Paperclip使用的@default_options变量。
这样,我就不必一遍又一遍地指定我想要的url、path和storage了。
我希望能更进一步,在其中包括验证,但我无法使其工作...
有什么想法吗?
编辑1:我想至少验证存在性和大小。
编辑2:我当前代码的一部分。
module Paperclip
 class Attachment
   def self.default_options
     if Rails.env != "production"
       @default_options = {
         :url => "/assets/:class/:attachment/:id/:style/:normalized_name",
         :path => ":rails_root/public/assets/:class/:attachment/:id/:style/:normalized_name",
         :default_style => :original,
         :storage       => :filesystem,
         :whiny         => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails]
         }
      else
       ...
      end
   end
 end
normalized_name是一个外部函数,特性:http://blog.wyeworks.com/2009/7/13/paperclip-file-rename 编辑3:
这篇博客:http://omgsean.com/2009/02/overriding-paperclip-defaults-for-your-entire-rails-app/展示了default_options哈希表中的validations键。
因此,虽然尚未找到,但可能是可行的。

可能想展示你所拥有的和尝试过的内容。 - Jimmy
我在这里并没有看到太多的问题。标准的存在和大小验证有什么问题吗? - Eric
我想把它们放在default_options哈希表中。 - apneadiving
有没有想法能否在这里设置文件类型?(例如将所有内容转换为PNG) - swrobel
1个回答

1

您无法将验证移动到default_options哈希中(因为这些验证是在附件类外部(在paperclip模块内部)执行的)。我的想法是,如果您的所有模型都有相同的验证,那么您可能需要考虑使用继承来减少代码重复。我建议不要将验证移动到初始化程序中。


我想知道为什么http://omgsean.com/2009/02/overriding-paperclip-defaults-for-your-entire-rails-app/中提到了一个validations键。 - apneadiving
它能工作吗?试一试... 我之前已经相当详细地查看了源代码,没有找到任何关于它的参考... - Kevin Sylvestre
我也尝试过覆盖“module InstanceMethods”,但没有成功。有什么线索吗? - apneadiving
我认为你需要对你的模型进行子类化,并将验证代码包含在父模型中。 - Kevin Sylvestre
谢谢你的回答,我会尽快尝试并确认你的解决方案,无论如何加一分;) - apneadiving

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接