Ruby On Rails : Devise Mailer : Customize / Override the Mailer

# app/mailers/my_devise_mailer.rb
class MyDeviseMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views

  # Overrides same inside Devise::Mailer
  def confirmation_instructions(record, token, opts={})
    opts[:from] = 'my_custom_from@domain.com'
    super
  end

  # Overrides same inside Devise::Mailer
  def reset_password_instructions(record, token, opts={})
    opts[:from] = 'my_custom_from@domain.com'
    super
  end

  # Overrides same inside Devise::Mailer
  def unlock_instructions(record, token, opts={})
    opts[:from] = 'my_custom_from@domain.com'
    super
  end
end

After that, change setting in devise.rb file

config.mailer = “MyDeviseMailer”

Don’t forget to restart the server because it is in config

Advertisements

Can we use helper method in controller?

Error:

Does anyone know why I get

undefined method `my_method' for #<MyController:0x1043a7410>

when I call my_method(“string”) from within my ApplicationController subclass? My controller looks like

class MyController < ApplicationController
  def show
    @value = my_method(params[:string])
  end
end

and my helper

module ApplicationHelper
  def my_method(string)
    return string
  end
end

and finally, ApplicationController

class ApplicationController < ActionController::Base
  after_filter :set_content_type
  helper :all
  helper_method :current_user_session, :current_user
  filter_parameter_logging :password
  protect_from_forgery # See ActionController::RequestForgeryProtection for details

Answer:

You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers.

EDIT: to be clear, I think a lot of the confusion (correct me if I’m wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side.

What If you want to use?

Include ApplicationHelper in application_controller.rb file like this:

class ApplicationController < ActionController::Base
  protect_from_forgery       
  include ApplicationHelper  
end

This way all the methods defined in application_helper.rb file will be available in the controller.

You can also include individual helpers in individual controllers.