Sha256: 95debc111e71550949f10fd09bc5065d02c2baf80faa01d5849a6431abc2c230

Contents?: true

Size: 1.61 KB

Versions: 10

Compression:

Stored size: 1.61 KB

Contents

require 'active_model'

module Progstr
  module Filer
    module Validation
      def validates_file_size_of(attribute, options)
        range = options[:in] || (0..1.0/0)
        min = options[:greater_than] || range.first
        max = options[:less_than]    || range.last
        allowed_range = (min..max)

        message = options[:message] || "File size not between #{min} and #{max} bytes."

        validates_with AttachmentPropertyValidator, :attributes => [attribute],
          :property => :size,
          :in        => allowed_range,
          :message   => message,
          :allow_blank => true,
          :allow_nil => true
      end

      def validates_file_extension_of(attribute, options)
        allowed = options[:allowed] || EverythingIncluded.new
        message = options[:message] || "File extension not allowed."

        validates_with AttachmentPropertyValidator, :attributes => [attribute],
          :property => :extension,
          :in        => allowed,
          :message   => message
      end

      class EverythingIncluded
        def include?
          true
        end
      end

      class AttachmentPropertyValidator < ActiveModel::Validations::InclusionValidator
        def initialize(options)
          @property = options[:property]
          super(options)
        end

        def validate_each(record, attribute, attachment)
          unless attachment.pre_validated
            property_value = attachment.send(@property)
            super(record, attribute, property_value) unless attachment.nil? || attachment.blank? || property_value.nil?
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
progstr-filer-0.8.11 lib/filer/validation.rb
progstr-filer-0.8.10 lib/filer/validation.rb
progstr-filer-0.8.9 lib/filer/validation.rb
progstr-filer-0.8.8 lib/filer/validation.rb
progstr-filer-0.8.7 lib/filer/validation.rb
progstr-filer-0.8.6 lib/filer/validation.rb
progstr-filer-0.8.5 lib/filer/validation.rb
progstr-filer-0.8.4 lib/filer/validation.rb
progstr-filer-0.8.3 lib/filer/validation.rb
progstr-filer-0.8.2 lib/filer/validation.rb