Skip to content

Instantly share code, notes, and snippets.

@cue232s
Created April 2, 2013 17:07
Show Gist options
  • Save cue232s/5294053 to your computer and use it in GitHub Desktop.
Save cue232s/5294053 to your computer and use it in GitHub Desktop.
I have two custom validators that check the dimensions of attachments set on my Model using Paperclip. For some reason, the second validator (promotion_image_dimensions) does not run when I manually upload an image that has invalid dimensions. It saves it to the database no problem. Oddly enough, my test show that this validation is being ran, a…
class PromotionAttachment < ActiveRecord::Base
belongs_to :promotion
attr_accessible :like_gate_image, :promotion_image
[:like_gate_image, :promotion_image].each do |file_name|
options = {
styles: {
medium: "300x300>}",
thumb: "100x100>"
},
:url => "/system/:attachment/:id/:style.:extension",
}
# If ENABLE_S3 returns TRUE (config/initializers/_tmg.rb) then files will be sent to s3 otherwise they will be stored locally
options.update({
storage: :s3,
s3_credentials: "#{::Rails.root}/config/aws.yml"
}) if ENABLE_S3
has_attached_file file_name, options
end
validate :like_gate_image_dimensions
validate :promotion_image_dimensions
def like_gate_image_dimensions
if like_gate_image.present? && !like_gate_image.exists?
dimensions = Paperclip::Geometry.from_file(like_gate_image.queued_for_write[:original].path)
if dimensions.width != 810 && dimensions.height > 199
errors.add(:like_gate_image,'width must be equal to 810px, and the height must be atleast 200px.')
end
puts "ran from 1"
end
end
def promotion_image_dimensions
if promotion_image.present? && !promotion_image.exists?
dimensions = Paperclip::Geometry.from_file(promotion_image.queued_for_write[:original].path)
if dimensions.width != 810 && dimensions.height > 199
errors.add(:promotion_image,'width must be equal to 810px, and the height must be atleast 200px.')
end
puts "ran from 2"
end
end
end
describe "validate the size of promotion_image" do
let(:promotion_attachment) {FactoryGirl.build(:promotion_attachment)}
subject { promotion_attachment }
context "Does not allow width smaller than 810px" do
before { promotion_attachment.promotion_image = File.new(Rails.root.join('spec', 'factories', 'width_to_small.png'))}
it { should have(1).error_on(:promotion_image)}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment