Skip to content

Instantly share code, notes, and snippets.

@giacomomacri
Last active October 25, 2017 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giacomomacri/6313c4aa28b381c1a77f16ac775d705a to your computer and use it in GitHub Desktop.
Save giacomomacri/6313c4aa28b381c1a77f16ac775d705a to your computer and use it in GitHub Desktop.
merge I18n keys from multiple files and write in a single file
en:
app:
my_key: ..
it:
app:
my_key: ..
def transform_hash(original, options={}, &block)
original.inject({}) do |result, (key,value)|
value = if (options[:deep] && Hash === value)
transform_hash(value, options, &block)
else
value
end
block.call(result,key,value)
result
end
end
I18n.backend.send(:init_translations)
translations = I18n.backend.send(:translations)
I18n.available_locales.each do |locale|
locale_hash = translations[locale][:app]
locale_translations = transform_hash(locale_hash, :deep => true) { |hash, key, value| hash[key.to_s] = value }
File.open("merged_#{locale}.yml", 'w+') { |f| f.write(locale_translations.to_yaml)}
end
@giacomomacri
Copy link
Author

giacomomacri commented Aug 17, 2017

In this case I need merging the locales key coming from the main app with keys coming from an engine. So all translations can be handled in one single file.
To avoid merging keys coming from various gem just add the app namespace to locale files you want to merge. Then I need to deep transform the keys of the hash in string for the yml conversion.

used on rails 4.2.8

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