module ValidateLimits::Extension::ClassMethods

Public Instance Methods

inherited(cls) click to toggle source
Calls superclass method
# File lib/validate-limits.rb, line 17
def inherited(cls)
  super.tap { cls.validate_limits }
end
validate_limits() click to toggle source
# File lib/validate-limits.rb, line 21
def validate_limits
  return if defined?(ActiveRecord::SchemaMigration) && self <= ActiveRecord::SchemaMigration
  return if abstract_class?
  return remove_instance_variable(:@table_name) unless table_name.in?(ActiveRecord::Base.connection.tables)

  columns_hash.values.each do |column|
    next if attributes_with_limit_validation.include?(column.name)

    case column.type
      when :string, :text
        self.attributes_with_limit_validation += [column.name]
        validate do
          value = send(column.name)
          value = value.to_s unless String === value
          errors.add(column.name, :too_long) if value.length > column.limit
        end

      when :integer
        next if column.name == primary_key

        self.attributes_with_limit_validation += [column.name]
        bits = column.limit * 8
        min  = -(2**(bits-1))
        max  = +(2**(bits-1))-1
        validates_numericality_of column.name, greater_than_or_equal_to: min,
                                               less_than_or_equal_to:    max,
                                               if:                       :"#{column.name}?"
    end
  end
end