Skip to content
This repository has been archived by the owner on Jul 13, 2023. It is now read-only.

Commit

Permalink
Add validates_attachment method to model
Browse files Browse the repository at this point in the history
  • Loading branch information
sikachu committed Mar 23, 2012
1 parent b3a63ed commit ee4107a
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lib/paperclip/validators.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
25 changes: 25 additions & 0 deletions test/validators_test.rb
Original file line number Diff line number Diff line change
@@ -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.