Skip to content

Instantly share code, notes, and snippets.

@pbrisbin
Last active December 30, 2015 23:39
Show Gist options
  • Save pbrisbin/7901815 to your computer and use it in GitHub Desktop.
Save pbrisbin/7901815 to your computer and use it in GitHub Desktop.
Spot some common mistakes in multi-language rails translations files.
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