Image par Antonios Ntoumas de Pixabay

I am about to release a huge rails project I have been working on for quite a while. This project is meant to replace an old app that manages a database of customers with emails. The new rails project uses Devise for authentication.

Before we push the final update to the production server, we need to find a way to import the users without sending confirmation emails, but still keep them unconfirmed until they actually login to the new system and provide a password. New registrations should also still be confirmable.

So I had to find a way to override an instance method. This is easy to do with a simple module:

# Module to be included in a User instance whenever we don't want to send an email
# Useful when importing users or for testing
module SkipConfirmationEmail 
  def self.included(base)
    base.send(:include, InstanceMethods)

    base.class_eval do
      alias_method :send_confirmation_instructions, :return_false
    end
  end 

  # Instance methods
  module InstanceMethods
    def return_false
      false
    end
  end
end

What this basically does is alias the send_confirmation_instructions method to a new return_false instance method we can inject into our model like this :

user = User.new
user.send(:include, SkipConfirmationEmail)

user.send_confirmation_instructions
#> false 

Therefore, my users will still have to confirm their account at first login on the new system, but won’t be notified when I import the database a few days before launch.

This can easily be adapted to serveral use cases, whenever you need to override an instance method in an exisiting Ruby class, as seen in this GitHub gist.