Class: ActiveStorageValidations::ContentTypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_storage_validations/content_type_validator.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#content_type(file) ⇒ Object



40
41
42
# File 'lib/active_storage_validations/content_type_validator.rb', line 40

def content_type(file)
  file.blob.present? && file.blob.content_type
end

#is_valid?(file) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
# File 'lib/active_storage_validations/content_type_validator.rb', line 44

def is_valid?(file)
  file_type = content_type(file)
  types.any? do |type|
    type == file_type || (type.is_a?(Regexp) && type.match?(file_type.to_s))
  end
end

#typesObject



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_storage_validations/content_type_validator.rb', line 22

def types
  return @types if defined? @types

  @types = (Array.wrap(options[:with]) + Array.wrap(options[:in])).compact.map do |type|
    if type.is_a?(Regexp)
      type
    else
      Marcel::MimeType.for(declared_type: type.to_s, extension: type.to_s)
    end
  end
end

#types_to_human_formatObject



34
35
36
37
38
# File 'lib/active_storage_validations/content_type_validator.rb', line 34

def types_to_human_format
  types
    .map { |type| type.to_s.split('/').last.upcase }
    .join(', ')
end

#validate_each(record, attribute, _value) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/active_storage_validations/content_type_validator.rb', line 5

def validate_each(record, attribute, _value)
  return true if !record.send(attribute).attached? || types.empty?

  files = Array.wrap(record.send(attribute))

  errors_options = { authorized_types: types_to_human_format }
  errors_options[:message] = options[:message] if options[:message].present?

  files.each do |file|
    next if is_valid?(file)

    errors_options[:content_type] = content_type(file)
    record.errors.add(attribute, :content_type_invalid, **errors_options)
    break
  end
end