Class: Paperclip::Validators::AttachmentContentTypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/paperclip/validators/attachment_content_type_validator.rb

Instance Method Summary (collapse)

Constructor Details

- (AttachmentContentTypeValidator) initialize(options)

A new instance of AttachmentContentTypeValidator



4
5
6
7
# File 'lib/paperclip/validators/attachment_content_type_validator.rb', line 4

def initialize(options)
  options[:allow_nil] = true unless options.has_key?(:allow_nil)
  super
end

Instance Method Details

- (Object) check_validity!



23
24
25
26
27
# File 'lib/paperclip/validators/attachment_content_type_validator.rb', line 23

def check_validity!
  unless options.has_key?(:content_type)
    raise ArgumentError, "You must pass in :content_type to the validator"
  end
end

- (Object) validate_each(record, attribute, value)



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/paperclip/validators/attachment_content_type_validator.rb', line 9

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

  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(', ')
    ))
  end
end