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
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
38 39 40 41 42 43 44 |
# File 'lib/active_storage_validations/content_type_validator.rb', line 38 def is_valid?(file) if [:with].is_a?(Regexp) [:with].match?(content_type(file).to_s) else content_type(file).in?(types) end end |
#types ⇒ Object
22 23 24 25 26 |
# File 'lib/active_storage_validations/content_type_validator.rb', line 22 def types (Array.wrap([:with]) + Array.wrap([:in])).compact.map do |type| Mime[type] || type end end |
#types_to_human_format ⇒ Object
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)) = { 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 |