written by seb on September 24th, 2006 @ 10:04 AM

I was wondering how I could validates the type of an object before creating or updating it.

As I didn’t find any already built tool for it, I made a small library that allow you to do such things

in your model:

Validates only if string_require.type is a String:

validates_type_of :string_require, :type => String

Validates only if float_require.type is a Float:

validates_type_of :float_require, :type => Float

And so on…

To use it you might need to create the following file:

File /lib/validates_type_of.rb:

module ActiveRecord
  class Errors
    @@default_error_messages[:invalid_type] ||= "wrong type. %s expected" 
  module Validations
    module ClassMethods
      # Validates whether the value of the specified object is from the correct type
      #   class Tariff < ActiveRecord::Base
      #     validates_type_of :price, :type => Float
      #   end
      # Configuration options:
      # * <tt>type</tt> - The acceptable type
      # * <tt>message</tt> - A custom error message (default is: "wrong type. %s expected")
      def validates_type_of(*attr_names)
        configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid_type], :on => :save }
        configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)

        # Ensure that the type is secified
        raise(ArgumentError, 'Type unspecified.') if configuration[:type].nil?

        message = configuration[:message] % configuration[:type]

        validates_each(attr_names, configuration) do |record, attr_name, value|
          if !value.blank?
            record.errors.add(attr_name, message) if !record.send("#{attr_name}_before_type_cast").is_a?(configuration[:type])

Now you will need to load at the end of your /config/environment.rb like this:

require 'validates_type_of'

Please be conscious that the use of this library is to your own risk, maybe to understand all it does might help you using it properly without dommaging your application.


Comments are closed