Skip to content

Instantly share code, notes, and snippets.

@vchervanev
Last active January 28, 2022 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vchervanev/ea6cb3749eede4c140606a3ec178f837 to your computer and use it in GitHub Desktop.
Save vchervanev/ea6cb3749eede4c140606a3ec178f837 to your computer and use it in GitHub Desktop.
Export locale/*.yml files into a CSV [filename, key, value]
require 'yaml'
require 'csv'
def iterate_kv(hash, prefix=nil, &block)
hash.each do |k,v|
current_prefix = [prefix, k].compact.join('.')
if v.is_a?(Hash)
iterate_kv(v, current_prefix, &block)
else
yield current_prefix, v
end
end
end
def iterate_file(path, &block)
iterate_kv(YAML.load_file(path), &block)
end
def iterate_files(base_dir='./config/locales')
Dir.glob(base_dir + '/**/*.yml').sort.each do |path|
iterate_file(path) do |k, v|
yield path, k, v
end
end
end
def ymls_to_csv(base_dir='./config/locales')
translations = Hash.new { |h,k| h[k] = {} }
iterate_files(base_dir) do |_f, k, v|
locale, key = k.match(/([^\.]+)\.(.+)/)[1..2]
translations[key][locale] = v
end
locales = ['en'] + (translations.values.flat_map(&:keys).uniq.sort - ['en'])
STDOUT.print(CSV.generate_line(['key'] + locales))
translations.each do |key, values|
STDOUT.print(CSV.generate_line([key] + locales.map { |loc| values[loc] } ))
end
end
# iterate_kv(a:1, b:{c:2, d:{e:3}}) { |k,v| puts [k,v].join(': ')}
# iterate_file('./config/locales/email/es.yml') { |k,v| puts [k,v].join(': ')}
ymls_to_csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment