Last active
August 29, 2015 14:02
-
-
Save remvee/851f1ff7d033791cc3ca to your computer and use it in GitHub Desktop.
Rake tasks to find missing translations by comparing available yml 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
namespace :i18n do | |
task en_bork: :environment do | |
I18n.locale = :en | |
en = I18n.t(".").except(:faker) | |
chef = replace_values!(en) do |val| | |
`echo #{val.inspect} | chef`.chomp.sub(/\s*Bork Bork Bork!/m, "") | |
end | |
File.open(Rails.root + "config/locales/en-bork.yml", "w") do |fd| | |
fd.write(YAML.dump("en-bork" => chef.deep_stringify_keys)) | |
end | |
end | |
task missing: :environment do | |
keys_per_locale = available_locales.map do |locale| | |
I18n.locale = locale | |
{ | |
locale => dot_deep_keys(I18n.t(".").except(:faker)).sort | |
} | |
end.reduce(:merge) | |
available_locales.each do |locale| | |
(available_locales - [locale]).each do |other| | |
d = keys_per_locale[other] - keys_per_locale[locale] | |
if d.present? | |
puts "Missing from #{locale} but available in #{other}:" | |
d.each { |k| puts " #{k}" } | |
end | |
end | |
end | |
end | |
end | |
def available_locales | |
Dir[Rails.root + "config/locales/*.yml"].map do |fn| | |
YAML.load(File.read(fn)) | |
end.reduce(&:deep_merge).keys.map(&:to_sym) | |
end | |
def dot_deep_keys(m, prefix = nil) | |
m.keys.map do |k| | |
[prefix, k].compact.join(".") | |
end + m.select do |_,v| | |
Hash === v | |
end.map do |k,v| | |
dot_deep_keys(v, [prefix, k].compact.join(".")) | |
end.flatten | |
end | |
def replace_values!(val, path = [], &block) | |
case val | |
when String | |
g = val.scan(/%{.*?}/m) | |
t = val.scan(/<.*?>/m) | |
i = j = 0 | |
yield(val).gsub(/%{.*?}/m) do |_| | |
g[i].tap{ i += 1 } | |
end.gsub(/<.*?>/m) do |_| | |
t[j].tap{ j += 1 } | |
end | |
when Hash | |
val.each do |k,v| | |
next if ["formats"].include?(path[-1]) | |
val[k] = replace_values!(v, path + [k], &block) | |
end | |
when Array | |
val.map { |v| replace_values!(v, path, &block) } | |
else | |
val | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment