Class: ContentTypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/content_type_validator.rb

Overview

Custom validator for attachments’ content types

Examples:


-> validates :image, content_type: :image
-> validates :image, content_type: [:jpg, :webp]
-> validates :image, content_type: [:image, :pdf]
-> validates :image, content_type: { in: :image, message: 'must be a valid image' }

Constant Summary collapse

EXPANSIONS =
{
  image:        %i[png jpeg jpg jpe pjpeg gif bmp svg webp],
  document:     %i[text txt docx doc xml pdf csv],
  calendar:     %i[ics],
  spreadsheet:  %i[xlsx xls],
  video:        %i[mpeg mpg mp3 m4a mpg4 aac webm mp4 m4v],
}.freeze

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/validators/content_type_validator.rb', line 20

def validate_each(record, attribute, value)
  # Support for optional attachments
  return unless value.present? && value.attached?

  keys   = EXPANSIONS.keys
  values = EXPANSIONS.values.flatten
  options = instance_values["options"]
  message = options.try(:[], :message) || "must have a valid content type"
  types = options[:with] || options[:in]

  # Ensure array and ensure symbols
  types = [types].flatten.compact.map(&:to_sym)

  allowed_types = []
  types.each do |types|
    if types.in?(keys)
      allowed_types << EXPANSIONS[types]
    elsif types.in?(values)
      allowed_types << types
    else
      raise("unknown content_type types: #{types}")
    end
  end
  allowed_types = allowed_types.flatten.map(&:to_sym).uniq

  # Make sure all attachments have this extension
  Array(value).each do |attachment|
    next if allowed_types.include?(attachment.filename.extension.to_sym)
    record.errors.add(attribute, message)
  end

end