Search code examples
ruby-on-railsrubydevise

How can I conditionalize Devise email content?


I want to include environment-specific information in my Devise emails (for example, to denote when emails are coming from a pre-production environment).

I am using Ruby 3.1.1, Rails 7.0.2.4, and Devise 4.8.1. I want to conditionalize content in devise emails (e.g., password reset) based on an environment variable.

In config/locales/devise.en.yml:

en:
  devise:
    mailer:
      reset_password_instructions:
        subject: "Reset password instructions"

In other config files I can do something like

ymlKey: "<%= ENV['SOME_ENV_NAME'] %>"

But when I try to do that in devise.en.yml:

        subject: "<%= ENV['SOME_ENV_NAME'] %>Reset password instructions"

the <%= %> isn't evaluated and is just sent as regular text.

How can I use an ENV variable or other conditional logic in devise emails?


Solution

  • There is no way to achieve that unless you develop a gem or a use a gem like this to do so as this is a .yml file and it has to be parsed somehow to make the string interpolation work as if it was a ruby file (.rb)

    Another way to achieve that, is by doing as below:

    in devise.en.yml:

    subject: "%{some_env_name} Reset password instructions"
    

    and in the line that sends the email you can do so:

    mail(to: user.email, subject: I18n.t('en.devise.mailer.reset_password_instructions.subject', :some_env_name => ENV['SOME_ENV_NAME']))
    

    Also you may try to do the following before applying what's above (I haven't tested it but it may work ... remove the double quotation) in devise.en.yml:

    subject: <%= ENV['SOME_ENV_NAME'] %>Reset password instructions