Where do I put helper methods for ActionMailer views?

Viewed 17917

I have a method that takes an array of strings and joins them so they do something like this:

>> my_arr
=> ["A", "B", "C"]
>> and_join(my_arr)
=> "A, B, and C"

Which I'd like my mailer to have access to so I can output some information into an email. I can't seem to find a good place to put it and putting it in the application_helper.rb file and it doesn't find it there. Where should it go?

6 Answers

In my case, for Rails 5.1, I had to use both include and helper methods, like this:

include ApplicationHelper
helper :application

And then just proceed to use the method normally.

class MyMailer < ActionMailer::Base
  include ApplicationHelper
  helper :application

  def my_mailer_method
    my_helper_method_declared_in_application_helper
    ..
  end
end

If you have some one off methods you want to use in the view, you can use helper_method directly in your mailer.

class MyMailer < ApplicationMailer
  def mailer
    mail to: '', subject: ''
  end

  private

  helper_method def something_to_use_in_the_view
  end
end

something_to_use_in_the_view will be available in your view.

Related