Class: Attachs::Extensions::ActiveRecord::Validations::AttachmentSizeValidator

Inherits:
AttachmentValidator
  • Object
show all
Defined in:
lib/attachs/extensions/active_record/validations/attachment_size_validator.rb

Constant Summary collapse

CHECKS =
{ less_than: :<, less_than_or_equal_to: :<=, greater_than: :>, greater_than_or_equal_to: :>= }

Instance Method Summary collapse

Methods inherited from AttachmentValidator

#validate_each

Constructor Details

#initialize(options) ⇒ AttachmentSizeValidator

Returns a new instance of AttachmentSizeValidator.



10
11
12
13
14
15
16
# File 'lib/attachs/extensions/active_record/validations/attachment_size_validator.rb', line 10

def initialize(options)
  if range = (options[:in] || options[:within])
    options[:less_than_or_equal_to] = range.max
    options[:greater_than_or_equal_to] = range.min
  end
  super
end

Instance Method Details

#validate_one(record, attribute, attachment) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/attachs/extensions/active_record/validations/attachment_size_validator.rb', line 18

def validate_one(record, attribute, attachment)
  unless attachment.blank?
    CHECKS.each do |name, operator|
      if options.has_key?(name)
        other = options[name]
        case other
        when Symbol
          other = record.send(other)
        when Proc
          other = other.call(record)
        end
        unless attachment.size.send(operator, other)
          record.errors.add attribute, :invalid
          attachment.errors.add :size, name, count: humanize_size(other)
        end
      end
    end
  end
end