class EchoUploads::Validation::UploadValidator

Public Instance Methods

validate_each(record, attr, val) click to toggle source
# 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