Module: Core::Models::Concerns::MimeTypable::ClassMethods

Defined in:
lib/core/models/concerns/mime_typable.rb

Overview

Submodule holding all the static methods add to the current subclass.

Author:

Instance Method Summary collapse

Instance Method Details

#mime_type(values) ⇒ Object

Defines the MIME type attribute with the given possible MIME types.

Parameters:

  • values (Array<String>)

    the possible MIME types, * can be used as wild cards.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/core/models/concerns/mime_typable.rb', line 14

def mime_type(values)

  # @!attribute [rw] mime_type
  #   @return [String] the MIME type of the file, obtained from the uploaded file.
  field :mime_type, type: String
        
  validates :mime_type, presence: {message: 'required'}

  validate :mime_type_validity, if: :mime_type?

  # Validates the validity of the MIME type by checking if it respects any of the given mime types.
  # If it does not respect any MIME types possible, it adds an error to the mime_type field and invalidates.
  define_method :mime_type_validity do
    checked_types = if values.is_a? Symbol
      self.send(values) rescue []
    else
      values
    end
    return true if checked_types.empty?
    checked_types.each do |type|
      type_regex = ::Regexp.new("^#{type.sub(/\*/, '(.+)')}$")
      return true if !type_regex.match(mime_type).nil?
    end
    errors.add(:mime_type, 'pattern')
  end
end