Skip to content

Commit

Permalink
Fix content_type validator to support blank/nil
Browse files Browse the repository at this point in the history
ContentTypeValidator now honors the `:allow_nil` and `:allow_blank` option.
  • Loading branch information
sikachu committed Apr 17, 2012
1 parent f647d68 commit 5eed1dc
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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(', ')
))
Expand Down
54 changes: 53 additions & 1 deletion test/validators/attachment_content_type_validator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"]
Expand Down

0 comments on commit 5eed1dc

Please sign in to comment.