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,
This is a very old question, but I don't see the full answer, so I will try as I didn't find another resource.
It depends on what you are doing with the methods that have been defined in the helper module. If they are class methods, and everything that's not called on a specific instance seem to be a class methods for 3.2.13, you need to use
extend ApplicationHelper
if an instance methods
include ApplicationHelper
and if you want to use them in a mailer view
helper ApplicationHelper
None of the *_path
helpers are accessible by default inside of an email. It is necessary instead to use the *_url
form of the wanted helper. So, for instance, instead of using user_path(@user)
it is necessary to use user_url(@user)
.
See at Action Mailer basics.
The single method version of promoting a method to being a helper that is available in ApplicationController also works in ActionMailer:
class ApplicationMailer < ActionMailer::Base
helper_method :marketing_host
def marketing_host
"marketing.yoursite.com"
end
end
from there you can call marketing_host
from any of your mailer views
If you want to call helper method from ActionMailer you need to include helper (module) in Mailer file as, if Helper module name is “UserHelper”, then need to write following in Mailer file
class CommentMailer < ActionMailer::Base
default :from => "Andre Fournier <andre@gfournier.com>"
add_template_helper(UserHelper)
end
Or
class CommentMailer < ActionMailer::Base
default :from => "Andre Fournier <andre@gfournier.com>"
include UserHelper
end
Hope this is helpful.
I'm not sure exactly what you are doing here, but when I want to access current_user from a mailer, I make a mailer method that I pass the user to as an argument:
class CommentMailer < ActionMailer::Base
default :from => "Andre Fournier <andre@gfournier.com>"
def blog_comment(user)
@recipients = user.email
@from = "andre@gfournier.com"
@sent_on = Time.now
@timestamp = Time.now
@user = user
end
end
With the above, @user, as well as all the other instance variables, are accessible from inside the mailer views ./views/comment_mailer/blog_comment.html.erb and ./views/comment_mailer/blog_comment.text.erb
Separately, you can make a helper called
comment_mailer_helper.rb
and put into that helper any methods that you want to be available to your mailer's views. This seems to me more like what you might want, regarding helpers, because helpers are designed to help views, whereas a mailer is analogous to a controller.
You could try mixing in the required helper module:
class CommentMailer < ActionMailer::Base
include ApplicationHelper
end