Reputation: 37
I have Rails (4) app and I'm using carrierwave to upload an image to an S3 bucket in production (and local in dev). It's all working, but I wanted to refactor my code.
My model:
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
After some refactoring, I have this:
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
The mount_uploader
, while ugly work fine. But I can't find a way to make picture_size
limit the size of each picture (from 1 to 11).
I can make it work using 11 times a different method or with a case operator. But i am trying to refactor.
I'd love to put my "for" loop in a method and call it but can't figure out how. if i define a method and call it all the image vanish and no file get uploaded (locally or on the S3 bucket)
Upvotes: 0
Views: 54
Reputation: 898
Try this:
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
Upvotes: 1