Module: ValidateLimits::Extension::ClassMethods

Defined in:
lib/validate-limits.rb

Instance Method Summary collapse

Instance Method Details

#inherited(cls) ⇒ Object



17
18
19
# File 'lib/validate-limits.rb', line 17

def inherited(cls)
  super.tap { cls.validate_limits }
end

#validate_limitsObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 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]
        validates_length_of column.name, maximum: column.limit

      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