What is the best practice to capitalize words in Rails?
internationalization, ruby, ruby-on-rails
Solution
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.
Problem
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) ```