Sha256: dcf52486ec5cee7fca7099c2d8be396c68382be79b3e79496e178976bfe3b321

Contents?: true

Size: 1.61 KB

Versions: 3

Compression:

Stored size: 1.61 KB

Contents

module Attachs
  module Extensions
    module ActiveRecord
      module Validations
        extend ActiveSupport::Concern

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

          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

          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

          private

          def humanize_size(size)
            ActiveSupport::NumberHelper.number_to_human_size size
          end

        end
        module ClassMethods

          def validates_attachment_size_of(*attr_names)
            validates_with AttachmentSizeValidator, _merge_attributes(attr_names)
          end

        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
attachs-4.0.0.2 lib/attachs/extensions/active_record/validations/attachment_size_validator.rb
attachs-4.0.0.1 lib/attachs/extensions/active_record/validations/attachment_size_validator.rb
attachs-4.0.0.0 lib/attachs/extensions/active_record/validations/attachment_size_validator.rb