Last Updated: February 25, 2016
·
1.296K
· alexvpopov

Regex for searching dynamically created I18n keys in Rails

Over the lifetime of a Rails app, as the code gets refactored, some translation keys become obsolete. Apart from manually checking up a key, there is no easy way to find obsolete keys. Tools like i18n-tasks alleviate the problem. However, they cannot detect dynamically created keys and might sometimes report false positives. For this reason, it is a good idea to list all the t-methods in the code, which do not contain strings of type 'namespace.subspace.key', but some method. Here is a regexp, which does just that:

(?<![a-z])t\([^'].{0,100}\)

The first part (?<![a-z]) is a negative lookbehind, so that methods, ending in t are not matched. The quantifier {0,100} part is a little tricky. If you use a * instead of {x,x}, you will get matches, such as:

t(somethinginhere) additional code someothermethod(using parenthesis)

and you might crash your editor, so you have to play with it (decrease or increase the second argument), to match your particular needs.