Class: MiniDefender::Rules::MimeTypes

Inherits:
MiniDefender::Rule show all
Defined in:
lib/mini_defender/rules/mime_types.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from MiniDefender::Rule

#active?, available?, #bails?, #coerce, #default_value, #defaults?, #error_message, #excluded?, #force_coerce?, #implicit?, #priority, #stops?, #with_message

Constructor Details

#initialize(types) ⇒ MimeTypes

Returns a new instance of MimeTypes.



7
8
9
10
11
12
13
14
# File 'lib/mini_defender/rules/mime_types.rb', line 7

def initialize(types)
  unless types.is_a?(Array) && types.all?{ |t| t.is_a?(String) }
    raise ArgumentError, 'Expected an array of strings.'
  end

  @types = types
  @file = false
end

Class Method Details

.make(args) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/mini_defender/rules/mime_types.rb', line 20

def self.make(args)
  unless args.length > 0
    raise ArgumentError, 'Expected at least one MIME type.'
  end

  new(args.map(&:downcase).map(&:strip))
end

.signatureObject



16
17
18
# File 'lib/mini_defender/rules/mime_types.rb', line 16

def self.signature
  'mime'
end

Instance Method Details

#message(attribute, value, validator) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/mini_defender/rules/mime_types.rb', line 36

def message(attribute, value, validator)
  if @file
    "The file should be one of the following types #{@types.to_sentence}"
  else
    'The field should be a file.'
  end
end

#passes?(attribute, value, validator) ⇒ Boolean

Returns:



28
29
30
31
32
33
34
# File 'lib/mini_defender/rules/mime_types.rb', line 28

def passes?(attribute, value, validator)
  @file = value.is_a?(ActionDispatch::Http::UploadedFile)
  content_type = Marcel::MimeType.for(value.read)
  value.rewind

  @file && @types.include?(content_type)
end