Search code examples
ruby-on-railsruby-on-rails-5constantsmailer

How do I get a constant recognized in my mailer file?


With Rails 5, how do I get a constant recognized in my mailer file? I have this file, app/mailers/user_notifier.rb,

class UserNotifier < ActionMailer::Base
    ...

  # send notification email to user about the price
  def send_confirmation_email(user_id)
    @user = User.find(user_id)
    mail( :to => @user.email,
    :subject => Constants::EMAIL_CONFIRMATION_SUBJECT )
  end

end

but when it gets to the line, ":subject => Constants::EMAIL_CONFIRMATION_SUBJECT )" it dies with the error

    uninitialized constant Constants::EMAIL_CONFIRMATION_SUBJECT

despite the fact i have the constant defined in my config/initializers/global.rb file

module Constants

  # Subject for email confirmations
  EMAIL_CONFIRMATION_SUBJECT = "Please confirm your email."

end

How do I fix this?


Solution

  • You don't need to prefix the constant with the module name. The constant will be available in the global scope.

    email:

    def send_confirmation_email(user_id)
     @user = User.find(user_id)
     mail( :to => @user.email,
      :subject => EMAIL_CONFIRMATION_SUBJECT )
    end
    

    config/initializers/global.rb

    EMAIL_CONFIRMATION_SUBJECT = "Please confirm your email."
    

    Although, I've got to suggest you use the internationalization in Rails since it's built just for this purpose http://guides.rubyonrails.org/i18n.html