Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
This is how we test that all translation keys match up between locales, in Rails.

This is how we test that all translation keys match up between locales.

Stuff that only goes in one locale (such as an admin section) or that can't be translated yet (if you use external translators) can simply go in files that don't match the path "config/locales/??.yml", like "config/locales/wip.fo.yml".

require 'yaml'
module I18nHelpers
PLURALIZATION_KEYS = %w[
zero
one
two
few
many
other
]
def load_locales
base_i18n_files.each do |file|
locale = File.basename(file, ".*")
hash = YAML.load_file(file)[locale]
locales_to_keys[locale] = get_flat_keys(hash)
end
end
def base_i18n_files
Dir["config/locales/*.yml"].select { |x| File.basename(x).match(/\A\w\w.yml\Z/) }
end
def locales_to_keys
@locales_to_keys ||= {}
end
def locales_to_documents
@locales_to_documents = locales_to_keys.keys.inject({}) do |hash, locale|
# E.g. [ "terms" ]
documents = Dir["config/locales/documents/*.#{locale}.*"].map { |file| File.basename(file, ".#{locale}.markdown") }
hash.merge locale => documents
end
end
def unique_keys
locales_to_keys.values.flatten.uniq.sort
end
def unique_documents
locales_to_documents.values.flatten.uniq.sort
end
def get_flat_keys(hash, path = [])
hash.map do |k, v|
new_path = path + [ k ]
# Ignore any pluralization differences.
if v.is_a?(Hash) && looks_like_plural?(v)
v = "Pretend it's a leaf."
end
case v
when Hash
get_flat_keys(v, new_path)
when String
new_path.join(".")
else
raise "wtf? #{ v }"
end
end.flatten
end
def looks_like_plural?(hash)
hash.keys.length > 1 && hash.keys.all? { |k| PLURALIZATION_KEYS.include?(k) }
end
end
require "support/i18n_helpers"
describe "The base i18n files" do
extend I18nHelpers
load_locales
locales_to_keys.each do |locale, keys|
unique_keys.each do |key|
it "should translate #{key} in locale #{locale} since it's present in some other locale" do
# Don't use "should include" or we get a ton of slow output.
keys.include?(key).should be_true, "Expected #{key} to be among the #{locale} locale's translation keys, but it wasn't"
end
end
end
locales_to_documents.each do |locale, documents|
unique_documents.each do |document|
it "should translate document #{document} in locale #{locale} since it's present in some other locale" do
documents.include?(document).should be_true, "Expected #{document} to be among the #{locale} locale's documents, but it wasn't"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment