Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add `validates_attachment` method to model

  • Loading branch information...
commit ee4107ab0986c68c01de1ff28160e106e355e819 1 parent b3a63ed
@sikachu sikachu authored
Showing with 55 additions and 0 deletions.
  1. +30 −0 lib/paperclip/validators.rb
  2. +25 −0 test/validators_test.rb
View
30 lib/paperclip/validators.rb
@@ -11,5 +11,35 @@ module Validators
extend HelperMethods
include HelperMethods
end
+
+ module ClassMethods
+ # This method is a shortcut to validator classes that is in
+ # "Attachment...Validator" format. It is almost the same thing as the
+ # +validates+ method that shipped with Rails, but this is customized to
+ # be using with attachment validators. This is helpful when you're using
+ # multiple attachment validators on a single attachment.
+ #
+ # Example of using the validator:
+ #
+ # validates_attachment :avatar, :presence => true,
+ # :content_type => { :content_type => "image/jpg" },
+ # :size => { :in => 0..10.kilobytes }
+ #
+ def validates_attachment(*attributes)
+ options = attributes.extract_options!.dup
+
+ Paperclip::Validators.constants.each do |constant|
+ if constant.to_s =~ /^Attachment(.+)Validator$/
+ validator_kind = $1.underscore.to_sym
+
+ if options.has_key?(validator_kind)
+ options[:"attachment_#{validator_kind}"] = options.delete(validator_kind)
+ end
+ end
+ end
+
+ validates(*attributes + [options])
+ end
+ end
end
end
View
25 test/validators_test.rb
@@ -0,0 +1,25 @@
+require './test/helper'
+
+class ValidatorsTest < Test::Unit::TestCase
+ def setup
+ rebuild_model
+ end
+
+ context "using the helper" do
+ setup do
+ Dummy.validates_attachment :avatar, :presence => true, :content_type => { :content_type => "image/jpg" }, :size => { :in => 0..10.kilobytes }
+ end
+
+ should "add the attachment_presence validator to the class" do
+ assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_presence }
+ end
+
+ should "add the attachment_content_type validator to the class" do
+ assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_content_type }
+ end
+
+ should "add the attachment_size validator to the class" do
+ assert Dummy.validators_on(:avatar).any?{ |validator| validator.kind == :attachment_size }
+ end
+ end
+end

0 comments on commit ee4107a

Please sign in to comment.
Something went wrong with that request. Please try again.