I'm working with languages in Rails, and I wonder what the best practice is when capitalizing a word.
en.yml:
hello: "hello"
application.html.erb:
<%= link_to t(:hello).capitalize, hello_path %> (with capitalization)
<%= link_to t(:hello), hello_path %> (without capitalization)
or
en.yml:
Hello: "Hello"
hello: "hello"
application.html.erb:
<%= link_to t(:Hello), hello_path %> (with capitalization)
<%= link_to t(:hello), hello_path %> (without capitalization)
capitalize is a String class method in Ruby which is used to return a copy of the given string by converting its first character uppercase and the remaining to lowercase.
Use capitalize . From the String documentation: Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
Ruby strings have methods to convert them to uppercase and lowercase. The method names of the methods are upcase and downcase respectively. Calling the downcase or upcase method on a string will return the lowercase or uppercase version of the string, but the original variable won't change.
The second one has a better chance of being correct. When to capitalize and when not to depends on the locale so you can't know if t(:hello).capitalize
will yield a correct result without looking at the surrounding context. A better approach than either would be to include the context in the symbol, something like this:
t(:hello_button)
and then in your English YAML:
hello_button: "Hello"
That way the translations can use whichever case is appropriate for the language in question. Also, sometimes English will use the same word for two things when other languages will use different words: consider orange the color and orange the fruit; hence the importance of context in your translations.
Furthermore, capitalize
only works on ASCII characters unless you throw an mb_chars
into the mix:
> 'µ'.capitalize
=> "µ"
> 'µ'.mb_chars.capitalize.to_s
=> "Μ"
You might not encounter a leading µ
but simple accents at the beginning of words are fairly common:
> 'éclair'.capitalize
=> "éclair"
> 'éclair'.mb_chars.capitalize.to_s
=> "Éclair"
This is just scratching the surface of the difficulties you'll face by assuming that all languages behave like English. Just wait until you have to start dealing with pluralization rules.
The basic rule in L10N is to treat user-facing strings as opaque blobs of data that you pull out of a database of some sort and show to the user without manipulation in between. Yes, this makes your code more complicated but correctness is sort of important.
While I'm here, attempting to translate individual words tends to produce an incomprehensible mess, you'll have better results if you translate entire sentences.
The first. Don't duplicate your data with just capitalization as the difference, it just makes it harder to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With