重构模型方法多个mount_uploader for carrierwave

时间:2016-02-10 10:23:09

标签: ruby-on-rails model refactoring carrierwave

我有Rails(4)应用程序,我使用carrierwave将图像上传到生产中的S3存储桶(以及dev中的本地存储桶)。它一切正常,但我想重构我的代码。

我的模特:

class Blogging < ActiveRecord::Base

mount_uploader :picture1, Picture1Uploader  
mount_uploader :picture2, Picture1Uploader  
mount_uploader :picture3, Picture1Uploader    
mount_uploader :picture4, Picture1Uploader  
mount_uploader :picture5, Picture1Uploader  
mount_uploader :picture6, Picture1Uploader  
mount_uploader :picture7, Picture1Uploader  
mount_uploader :picture8, Picture1Uploader  
mount_uploader :picture9, Picture1Uploader  
mount_uploader :picture10, Picture1Uploader  
mount_uploader :picture11, Picture1Uploader  
validate :picture_size  


private
  def picture_size
    if picture1.size > 5.megabytes
        errors.add(:picture1, "should be less than 5 MB")
    end
  end


end

经过一些重构后,我有了这个:

class Blogging < ActiveRecord::Base


for i in 1..11 
 mount_uploader :"picture#{i}", Picture1Uploader
end


validate :picture_size
validates :picture1, :news_title, :news_body, presence: true 



private

 def picture_size
    pics = Array.new(11) {|i| "picture#{i+1}"} 
        pics.each do |p|
        if p.size > 5.megabytes
        errors.add(:picture1, "should be less than 5 MB")
        end
     end
 end
end

mount_uploader,虽然丑陋的工作很好。但我无法找到一种方法让picture_size限制每张图片的大小(从1到11)。

  • 我可以使用11次不同的方法或使用案例操作符来使其工作。但我正在尝试重构。

  • 我喜欢把我的&#34;用于&#34;循环一个方法并调用它,但无法弄清楚如何。如果我定义一个方法,并调用它所有图像消失,没有文件上传(本地或S3桶)

1 个答案:

答案 0 :(得分:1)

试试这个:

def picture_size
  pics = Array.new(11) {|i| "picture#{i+1}"}.each do |pic_name|
    p = self.send pic_name
    if p.size > 5.megabytes
      self.errors.add(:picture1, "should be less than 5 MB")
    end
  end
end