Search code examples
ruby-on-railsdeviseflash-message

string interpolation in devise flash messages?


I'm new to RoR and I would like to personalise the Devise flash messages to use the name of the current user.

I've seen that the original file includes the following line:

devise.en.yml

  failure: "Could not authenticate you from %{kind} because \"%{reason}\"."

So I've applied the same rule to:

sessions:
  signed_in: "Welcome back!."
  signed_out: "See you soon!."

-

sessions:
  signed_in: "Welcome back! \"#{current_user.first_name}\"."
  signed_out: "See you soon! \"#{current_user.first_name}\"."

but the code is not executing, and prints the whole sentence as string.

Any help would be appreciated! :)


Solution

  • It should be

    sessions:
      signed_in: "Welcome back! %{name}."
      signed_out: "See you soon! %{name}."
    

    And you must call it like:

    t('sessions.signed_in', name: current_user.first_name)
    t('sessions.signed_out', name: current_user.first_name)
    

    You can't use ruby interpolation in yml file but you can pass variable to the translation and use yml interpolation syntax %{}