Commit 5eed1dcb by Prem Sichanugrist

Fix content_type validator to support blank/nil

ContentTypeValidator now honors the `:allow_nil` and `:allow_blank` option.
parent f647d680
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(', ')
))
......
......@@ -24,6 +24,58 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
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 @@ class AttachmentContentTypeValidatorTest < Test::Unit::TestCase
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"]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment