Class: EchoUploads::Validation::UploadValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/echo_uploads/validation.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr, val) ⇒ Object



11
12
13
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/echo_uploads/validation.rb', line 11

def validate_each(record, attr, val)
  # Presence validation
  if options[:presence]
    unless record.send("has_#{attr}?")
      record.errors[attr] << (
        options[:message] ||
        'must be uploaded'
      )
    end
  end
  
  # File size validation
  if options[:max_size]
    unless options[:max_size].is_a? Numeric
      raise(ArgumentError,
        "validates :#{attr}, :upload called with invalid :max_size option. " +
        ":max_size must be a number, e.g. 1.megabyte"
      )
    end
    
    if val.present?
      unless val.respond_to?(:size)
        raise ArgumentError, "Expected ##{attr} to respond to #size"
      end
      
      if val.size > options[:max_size]
        record.errors[attr] << (
          options[:message] ||
          "must be smaller than #{options[:max_size].to_i} bytes"
        )
      end
    end
  end
  
  # Extension validation
  if options[:extension]
    unless options[:extension].is_a? Array
      raise(ArgumentError,
        "validates :#{attr}, :upload called with invalid :extension option. " +
        ":extension must be an array of extensions like ['.jpg', '.png']"
      )
    end
    
    if val.present?
      unless val.respond_to?(:original_filename)
        raise ArgumentError, "Expected ##{attr} to respond to #original_filename"
      end

      ext = ::File.extname(val.original_filename).downcase
      unless options[:extension].include?(ext.downcase)
        record.errors[attr] << (
          options[:message] ||
          "must have one of the following extensions: #{options[:extension].join(',')}"
        )
      end
    end
  end
end