Module: ValidatesLengthsFromDatabase::InstanceMethods

Defined in:
lib/validates_lengths_from_database.rb

Instance Method Summary collapse

Instance Method Details

#validate_lengths_from_databaseObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/validates_lengths_from_database.rb', line 34

def validate_lengths_from_database
  options = self.class.validate_lengths_from_database_options

  if options[:only]
    columns_to_validate = options[:only].map(&:to_s)
  else
    columns_to_validate = self.class.column_names.map(&:to_s)
    columns_to_validate -= options[:except].map(&:to_s) if options[:except]
  end

  columns_to_validate.each do |column|
    column_schema = self.class.columns.find {|c| c.name == column }
    next if column_schema.nil?
    next if column_schema.respond_to?(:array) && column_schema.array

    if [:string, :text, :integer, :decimal, :float].include?(column_schema.type)      
      column_limit = options[:limit][column_schema.type] || column_schema.limit          

      ActiveModel::Validations::LengthValidator.new(:maximum => column_limit, :allow_blank => true, :attributes => [column]).validate(self) if column_limit

      if column_schema.type == :decimal && column_schema.precision && column_schema.scale

        max_val = (10 ** column_schema.precision)/(10 ** column_schema.scale)

        ActiveModel::Validations::NumericalityValidator.new(:less_than => max_val, :allow_blank => true, :attributes => [column]).validate(self)
      end
    end

  end
end