Search code examples
ruby-on-railsinternationalizationrails-i18n

Using a/an on an I18n message


I have the following error message on my en.yml file:

invalid_transition: "Cannot %{action} a %{state} timesheet"

Problem is that sometimes the state can be approved, other times it can be rejected.

With that, the error can end up being mispelled like "Cannot submit a approved timesheet", instead of "an approved timesheet".

Does Rails provide this flexibility in I18n?


Solution

  • The most simple answer to your question, I think, would be to pass in the entire state with the correct indefinite article together.

    There's a question that looks at how to prepend "a" or "an" depending on a given word. A short answer is that there's a gem indefinite_article that does it.

    Your translation then becomes:

    invalid_transition: "Cannot %{action} %{state_with_article} timesheet"
    

    Then call the I18n.t and pass in "a rejected" or "an approved" as a variable to interpolate.

    However, if you want to get your hands a bit dirtier you may be able to use the i18n-inflector gem and it's companion i18n-inflector-rails gem. For many languages the choice is more complicated than in English because of different genders and tenses affecting the choice of indefinite article. (Disclaimer: I've not used either of those gems but they look like they would help you solve the problem).