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



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

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

#is_valid?(file) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
# File 'lib/active_storage_validations/content_type_validator.rb', line 38

def is_valid?(file)
  if options[:with].is_a?(Regexp)
    options[:with].match?(content_type(file).to_s)
  else
    content_type(file).in?(types)
  end
end

#typesObject



22
23
24
25
26
# File 'lib/active_storage_validations/content_type_validator.rb', line 22

def types
  (Array.wrap(options[:with]) + Array.wrap(options[:in])).compact.map do |type|
    Mime[type] || type
  end
end

#types_to_human_formatObject



28
29
30
31
32
# File 'lib/active_storage_validations/content_type_validator.rb', line 28

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