Skip to content

Instantly share code, notes, and snippets.

@johnnypez
Created August 19, 2013 20:21
Show Gist options
  • Save johnnypez/6273624 to your computer and use it in GitHub Desktop.
Save johnnypez/6273624 to your computer and use it in GitHub Desktop.
syncs keys from en.yml to other exisiting locale files
#!/usr/bin/env ruby
require 'yaml'
require 'active_support'
RAILS_ROOT = File.expand_path(File.dirname(__FILE__) + '/../')
files = Dir.glob("#{RAILS_ROOT}/config/locales/*.yml")
locales = files.map{|f| File.basename(f, '.yml')}
def flat_hash(hash, k = nil)
return {k => hash} unless hash.is_a?(Hash)
hash.inject({}){ |h, v| h.merge! flat_hash(v[-1], [k,v[0]].compact.join('.')) }
end
def load_yaml(f)
YAML.load(File.read(f))
end
def locale_code(f)
File.basename(f, '.yml')
end
en_file = files.grep(/en\.yml/).first
en = flat_hash(load_yaml(en_file)["en"])
(files - [en]).each do |f|
locale = locale_code f
translations = flat_hash load_yaml(f)[locale]
en.each do |key, value|
translations[key] = value unless translations.has_key?(key)
end
rebuild = {}
translations.sort.each do |k,v|
unflattened = k.split('.').reverse.inject(v){|a, b| Hash[b, a]}
rebuild.deep_merge! unflattened
end
file = File.open(f, 'w')
file.write Hash[locale,rebuild].to_yaml
file.close
end
@ruby24
Copy link

ruby24 commented Dec 19, 2013

Thanks, this is exactly what we were looking for!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment