Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Fix content_type validator to support blank/nil

ContentTypeValidator now honors the `:allow_nil` and `:allow_blank` option.
  • Loading branch information...
commit 5eed1dcb785e8b42ea7881b1bd822394df6aa3a0 1 parent f647d68
@sikachu sikachu authored
View
9 lib/paperclip/validators/attachment_content_type_validator.rb
@@ -1,12 +1,19 @@
module Paperclip
module Validators
class AttachmentContentTypeValidator < ActiveModel::EachValidator
+ def initialize(options)
+ options[:allow_nil] = true unless options.has_key?(:allow_nil)
+ super
+ end
+
def validate_each(record, attribute, value)
attribute = "#{attribute}_content_type".to_sym
value = record.send(:read_attribute_for_validation, attribute)
allowed_types = [options[:content_type]].flatten
- if value.present? && allowed_types.none? { |type| type === value }
+ return if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
+
+ if allowed_types.none? { |type| type === value }
record.errors.add(attribute, :invalid, options.merge(
:types => allowed_types.join(', ')
))
View
54 test/validators/attachment_content_type_validator_test.rb
@@ -24,6 +24,58 @@ def build_validator(options)
end
end
+ context "with :allow_nil option" do
+ context "as true" do
+ setup do
+ build_validator :content_type => "image/png", :allow_nil => true
+ @dummy.stubs(:avatar_content_type => nil)
+ @validator.validate(@dummy)
+ end
+
+ should "allow avatar_content_type as nil" do
+ assert @dummy.errors[:avatar_content_type].blank?
+ end
+ end
+
+ context "as false" do
+ setup do
+ build_validator :content_type => "image/png", :allow_nil => false
+ @dummy.stubs(:avatar_content_type => nil)
+ @validator.validate(@dummy)
+ end
+
+ should "not allow avatar_content_type as nil" do
+ assert @dummy.errors[:avatar_content_type].present?
+ end
+ end
+ end
+
+ context "with :allow_blank option" do
+ context "as true" do
+ setup do
+ build_validator :content_type => "image/png", :allow_blank => true
+ @dummy.stubs(:avatar_content_type => "")
+ @validator.validate(@dummy)
+ end
+
+ should "allow avatar_content_type as blank" do
+ assert @dummy.errors[:avatar_content_type].blank?
+ end
+ end
+
+ context "as false" do
+ setup do
+ build_validator :content_type => "image/png", :allow_blank => false
+ @dummy.stubs(:avatar_content_type => "")
+ @validator.validate(@dummy)
+ end
+
+ should "not allow avatar_content_type as blank" do
+ assert @dummy.errors[:avatar_content_type].present?
+ end
+ end
+ end
+
context "with an allowed type" do
context "as a string" do
setup do
@@ -48,7 +100,7 @@ def build_validator(options)
assert @dummy.errors[:avatar_content_type].blank?
end
end
-
+
context "as a list" do
setup do
build_validator :content_type => ["image/png", "image/jpg", "image/jpeg"]
Please sign in to comment.
Something went wrong with that request. Please try again.