Last active
December 30, 2015 23:39
-
-
Save pbrisbin/7901815 to your computer and use it in GitHub Desktop.
Spot some common mistakes in multi-language rails translations files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'yaml' | |
# {a,{b,{c}} => [a, a.b, a.b.c] | |
def parse_keys(hash, keys = [], prefix = nil) | |
hash.each do |k, v| | |
key = [prefix, k].compact.join('.') | |
if v.is_a?(Hash) | |
parse_keys(v, keys, key) | |
else | |
keys << key | |
end | |
end | |
keys | |
end | |
# spots only simple uses: t("a.b"), {{t "a.b"}} | |
def used?(key) | |
greps = [ | |
%|git grep -Fq 'Translation="#{key}"'|, | |
%|git grep -Fq "Translation='#{key}'"|, | |
%|git grep -Fq '{{t "#{key}"'|, | |
%|git grep -Fq "{{t '#{key}'"|, | |
%|git grep -Fq 't("#{key}"'|, | |
%|git grep -Fq "t('#{key}'"| | |
] | |
greps.any? { |cmd| system(cmd) } | |
end | |
locales = {} | |
Dir.glob('config/locales/*.yml').each do |file| | |
yaml = YAML.load(File.read(file)) | |
locale = yaml.first.first | |
locales[locale] = parse_keys(yaml[locale]) | |
end | |
locales.each do |locale,keys| | |
other_locales = locales.reject { |k,_| k == locale } | |
keys.each do |key| | |
other_locales.each do |other_local,other_keys| | |
unless other_keys.include?(key) | |
$stderr.puts "[error]: #{locale}.#{key} not present in #{other_locale}" | |
end | |
end | |
end | |
end | |
locales.values.flatten.uniq.each do |key| | |
unless used?(key) | |
$stderr.puts "[warning]: #{key}: does not appear to be used" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment