Sha256: 8988ac986188eac9ef6933a07033a1ce2b6c8bc602f26d3ae4809f1d96c21fca

Contents?: true

Size: 1.3 KB

Versions: 8

Compression:

Stored size: 1.3 KB

Contents

module ActiveRecord
  module Validations
    module ClassMethods
      # Automatically validates the column against the schema definition
      # for nullability, format, and enumerations. Handles integers, floats,
      # enumerations, and string limits.
      #
      # Usage: validates_columns :severity, :name
      def validates_columns(*column_names)
        begin
          cols = columns_hash
          column_names.each do |name|
            col = cols[name.to_s]
            raise ArgumentError, "Cannot find column #{name}" unless col
            
            # test for nullability
            validates_presence_of(name) if !col.null
            
            # Test various known types.
            case col.type
            when :enum
              validates_inclusion_of name, :in => col.limit, :allow_nil => true
              
            when :integer, :float
              validates_numericality_of name, :allow_nil => true
              
            when :string
              if col.limit
                validates_length_of name, :maximum => col.limit, :allow_nil => true
              end
            end
          end
        rescue ActiveRecord::StatementInvalid=>e
          raise e unless e.message.include?("42S02") # swallow the exception if its for a missing table
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 4 rubygems

Version Path
mysql_enum_column-0.2.0 lib/enum/validations.rb
dg-enum_column4-0.1.7 lib/enum/validations.rb
dg-enum_column4-0.1.6 lib/enum/validations.rb
dg-enum_column4-0.1.4 lib/enum/validations.rb
enum_column_strict-0.0.2 lib/enum/validations.rb
enum_column_strict-0.0.1 lib/enum/validations.rb
enum_column3-0.1.4 lib/enum/validations.rb
enum_column3-0.1.3 lib/enum/validations.rb