Skip to content

Instantly share code, notes, and snippets.

@hagenburger
Last active March 24, 2016 17:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hagenburger/b96fada108d05d3c8f52 to your computer and use it in GitHub Desktop.
Save hagenburger/b96fada108d05d3c8f52 to your computer and use it in GitHub Desktop.
Optimized Rails I18n format

Traditional way

my_key_link: 'World'
my_key: 'Hello %{link}!'                      link: link_to(t('my_key_link'), 'xy')
'Hello <a href="xy">World</a>!'
  • Need to check if raw is required everytime
  • Translators can loose the context
  • It’s not clear if “World” in the first line needs to be upper or lowercase

Optimized way

Normal

'Hello world!'
'Hello world!'

Italic

'Hello *world!*'
'Hello <i>world!</i>'

Bold

'Hello **world!**'
'Hello <b>world!</b>'

Bold + Substitution

'Hello **%{name}!**'                                          name: 'Homer'
'Hello <b>Homer!</b>'

Typographic quotation marks (“”, „“, «», …) are automatically set by defining <html lang="en">:

'Hello "%{name}!"'                                            name: 'Marge'
'Hello <q>Marge!</q>'

Replacements within replacements

'Hello %{link:world}!'                                        link: link_to('%', 'xy')
'Hello <a href="xy">world</a>!'

All combined

'*Hello* %{link:**beautiful** world}!'                        link: link_to('%', 'xy')
'<i>Hello</i> <a href="xy"><b>beautiful</b> world</a>!'
module ApplicationHelper
def t(id, replacements = {})
text = translate(id)
text.gsub! /[&"'><]/, ERB::Util::HTML_ESCAPE
{ q: '&quot;', b: '\*\*', i: '\*' }.each do |tag, symbol|
text.gsub! /#{symbol}(.+?)#{symbol}/, "<#{tag}>\\1</#{tag}>"
end
# Upper part could be cached.
replacements.each do |key, value|
text.gsub!(/%\{#{key}(:(.+?))?\}/) { value.gsub('%', $2 || '%') )
end
text.html_safe
end
end
@terry90
Copy link

terry90 commented Mar 24, 2016

Line 14

text.gsub!(/%\{#{key}(:(.+?))?\}/) { value.gsub('%', $2 || '%') )

Should be

text.gsub!(/%\{#{key}(:(.+?))?\}/) { value.to_s.gsub('%', $2 || '%') }

To handle integers repalcements + fix typo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment