Ruby Rails : How to bypass skip validation in Devise

Since my last post with email validations, I was looking for a solution to integrate it with devise

Sadly for me, devise implements the old way of validating email with regexp :

# From devise gem version 1.1.3
validates_format_of     :email, :with  => email_regexp, :allow_blank => true

Well, as I don’t want to hack activemodel’s code, I prefer to skip the validates_format_of method in User class.

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, :lockable and :timeoutable
  include SkipableMethod
 
  # Devise is great but uses the oldest way with regexp to validate email
  skip_and_restore_method(:validates_format_of) do
    devise :database_authenticatable, :registerable,
      :recoverable, :rememberable, :trackable, :validatable
  end
 
  # Replace with a validation of my own
  validates :email, :email => true, :presence => true
 
  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
 
end

And then the library :

module SkipableMethod
  module ClassMethods
 
    protected
    def __skip_method(*args);end
 
    def skip_and_restore_method(*method_names,&block)
      method_names.each do |method_name|
        instance_eval <<-EVAL
        alias #{method_name}_skipped #{method_name}
        alias #{method_name} __skip_method
        EVAL
      end
 
      yield
 
      method_names.each do |method_name|
        instance_eval <<-EVAL
        alias #{method_name} #{method_name}_skipped
        undef #{method_name}_skipped
        EVAL
      end
    end
  end
 
  def self.included(receiver)
    receiver.extend         ClassMethods
  end
end

TODO :

Some tests 😀

5 thoughts on “Ruby Rails : How to bypass skip validation in Devise

  1. Why not just remove the “:validatable” from your devise list and then write your own validations for the User model?

  2. Thanks for writing this, it and valid_email let me do just what I want.

    I was wondering what license you intended this to be published with? I would like to use it in a project where I am required to be careful about licenses.

    Have you consider putting this into a gem?

Leave a Reply

Your email address will not be published. Required fields are marked *