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
47
48
49
50
# 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