Class: ActiveStorageValidations::ContentTypeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveStorageValidations::ContentTypeValidator
- Defined in:
- lib/active_storage_validations/content_type_validator.rb
Overview
:nodoc:
Instance Method Summary collapse
- #content_type(file) ⇒ Object
- #is_valid?(file) ⇒ Boolean
- #types ⇒ Object
- #types_to_human_format ⇒ Object
- #validate_each(record, attribute, _value) ⇒ Object
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
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 |
#types ⇒ Object
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([:with]) + Array.wrap([: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_format ⇒ Object
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)) = { authorized_types: types_to_human_format } [:message] = [:message] if [:message].present? files.each do |file| next if is_valid?(file) [:content_type] = content_type(file) record.errors.add(attribute, :content_type_invalid, **) break end end |