Creating a Ruby on Rails Mailer

So this is a pretty easy task to accomplish.

From the command line switch to the directory where your app is located. Enter the following command

  script/generate mailer notifier
This will create a model called notifer.rb, a folder under the views folder called notifier, it will create other files as well but these are the main two to be concerned with.

In views/notifier is where we will be creating erb templates to be the actual email that gets sent out to the end user.

In the notifier model, you'll want to setup functions that you will call from your controller in order to send the email. Here are a couple of examples I have created for my user email functions

class UserNotification < ActionMailer::Base
  def password_reset_code(user)
    @recipients   = "#{user.email}"
    @from         = "Domain.com "
    @subject      = "Your requested a password reset."
    @sent_on      = Time.now
    @body         = { :user =< user }
  end
  
  def reset_notification(user)
    @recipients   = "#{user.email}"
    @from         = "Domain.com "
    @subject      = "Your password has been reset."
    @sent_on      = Time.now
    @body         = { :user =< user }
  end
end
As you can probably tell this will setup two emails one for sending a reset code the other to verify the password has been reset.

In your controller, you simply call the Model in my example its called UserNotification.

UserNotification.deliver_password_reset_code(@user)
The @user is an instance variable I created a couple of lines up that is a simple query to find the current user that is logged in. Notice you always prepend the Mailer function name with "deliver_".

Back up in our UserNotification functions you see for the @body variable we assign a simple hash. The hash will contain a link to all the model data passed into it. And will make that data available in the view. To reference the data simply use the instance variable, in our case @user to gain access to the model data.

Here is an example view

Hi @user.email,

Here is your password reset code:

@user.password_reset_code

Please copy and paste the url below into your browser in order to reset your password:

http://domain.com/reset/#{@user.password_reset_code}

Comments

Popular posts from this blog

Console over SSH (ONTAP)

Cacti Monitor Server Step by Step Ubuntu

Brocade Zone Setup