class Paperclip::Validators::AttachmentSizeValidator
def self.helper_method_name
def self.helper_method_name :validates_attachment_size end
def check_validity!
def check_validity! unless (AVAILABLE_CHECKS + [:in]).any? { |argument| options.has_key?(argument) } raise ArgumentError, "You must pass either :less_than, :greater_than, or :in to the validator" end end
def extract_option_value(option, option_value)
def extract_option_value(option, option_value) if option_value.is_a?(Range) if [:less_than, :less_than_or_equal_to].include?(option) option_value.max else option_value.min end else option_value end end
def extract_options(options)
def extract_options(options) if range = options[:in] if !options[:in].respond_to?(:call) options[:less_than_or_equal_to] = range.max options[:greater_than_or_equal_to] = range.min else options[:less_than_or_equal_to] = range options[:greater_than_or_equal_to] = range end end end
def human_size(size)
def human_size(size) if defined?(ActiveSupport::NumberHelper) # Rails 4.0+ ActiveSupport::NumberHelper.number_to_human_size(size) else storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true) unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => size.to_i, :raise => true) storage_units_format.gsub(/%n/, size.to_i.to_s).gsub(/%u/, unit).html_safe end end
def initialize(options)
def initialize(options) extract_options(options) super end
def max_value_in_human_size(record)
def max_value_in_human_size(record) value = options[:less_than_or_equal_to] || options[:less_than] value = value.call(record) if value.respond_to?(:call) value = value.max if value.respond_to?(:max) human_size(value) end
def min_value_in_human_size(record)
def min_value_in_human_size(record) value = options[:greater_than_or_equal_to] || options[:greater_than] value = value.call(record) if value.respond_to?(:call) value = value.min if value.respond_to?(:min) human_size(value) end
def validate_each(record, attr_name, value)
def validate_each(record, attr_name, value) base_attr_name = attr_name attr_name = "#{attr_name}_file_size".to_sym value = record.send(:read_attribute_for_validation, attr_name) unless value.blank? options.slice(*AVAILABLE_CHECKS).each do |option, option_value| option_value = option_value.call(record) if option_value.is_a?(Proc) option_value = extract_option_value(option, option_value) unless value.send(CHECKS[option], option_value) error_message_key = options[:in] ? :in_between : option [ attr_name, base_attr_name ].each do |error_attr_name| record.errors.add(error_attr_name, error_message_key, filtered_options(value).merge( :min => min_value_in_human_size(record), :max => max_value_in_human_size(record), :count => human_size(option_value) )) end end end end end