Module: Virtuaservices::Concerns::MimeTypable::ClassMethods

Defined in:
lib/virtuaservices/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.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/virtuaservices/concerns/mime_typable.rb', line 13

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
    values.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