Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access helpers from mailer?

I have trying to access helper methods from a rails 3 mailer in order to access the current user for the session.

I put the helper :application in my mailer class, which seems to work, except the methods defined therein are not available to my mailer (i get undefined errors). Does anyone know how this is supposed to work?

Here's my class:

class CommentMailer < ActionMailer::Base   default :from => "Andre Fournier <[email protected]>"    helper :application end 

Thanks, Sean

like image 466
Sean O'Hara Avatar asked Feb 08 '11 19:02

Sean O'Hara


People also ask

What are view helpers in Rails?

A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.


2 Answers

To enable you to access application helpers from the ActionMailer views, try adding this:

add_template_helper(ApplicationHelper) 

To your ActionMailer (just under your default :from line).

like image 185
William Denniss Avatar answered Oct 04 '22 03:10

William Denniss


Use helper ApplicationHelper

class NotificationsMailer < ActionMailer::Base    default from: "Community Point <[email protected]>"   helper ApplicationHelper   helper NotificationMailerHelper    # ...other code... 

NOTE: These helper methods are only available to the Views. They are not available in the mailer class (NotificationMailer in my example).

If you need them in the actual mailer class, use include ApplicationHelper, like so:

class NotificationMailer < ActionMailer::Base    include ApplicationHelper    # ... the rest of your mailer class.  end 

From this other SO question.

like image 42
Joshua Pinter Avatar answered Oct 04 '22 04:10

Joshua Pinter