Created
August 4, 2011 16:03
-
-
Save Govinda-Fichtner/1125517 to your computer and use it in GitHub Desktop.
I18n Utils
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
# orginally from the I18n_backend_database plugin | |
# http://github.com/dylanz/i18n_backend_database/ | |
# slimed down to allow only import of yaml files for importing locale information | |
# gets called from a rake task in Rails.root/lib/comuungo.rake | |
class I18nUtil | |
# Create tanslation records from the YAML file. Will create the required locales if they do not exist. | |
def self.load_from_yml(file_name) | |
data = YAML::load(IO.read(file_name)) | |
data.each do |code, translations| | |
locale = Globalize::Backend::Database::Locale.find_or_create_by_code(code) | |
backend = I18n::Backend::Simple.new | |
keys = extract_i18n_keys(translations) | |
keys.each do |key| | |
value = backend.send(:lookup, code, key) | |
pluralization_index = 1 | |
if key.ends_with?('.one') | |
key.gsub!('.one', '') | |
end | |
if key.ends_with?('.other') | |
key.gsub!('.other', '') | |
pluralization_index = 0 | |
end | |
if value.is_a?(Array) | |
value.each_with_index do |v, index| | |
create_translation(locale, "#{key}", index, v) unless v.nil? | |
end | |
else | |
create_translation(locale, key, pluralization_index, value) | |
end | |
end | |
end | |
end | |
# Finds or creates a translation record and updates the value | |
def self.create_translation(locale, key, pluralization_index, value) | |
translation = locale.translations.find_by_key_and_pluralization_index(Globalize::Backend::Database::Translation.hk(key), pluralization_index) # find existing record by hash key | |
unless translation # or build new one with raw key | |
translation = locale.translations.build(:key =>key, :pluralization_index => pluralization_index) | |
#puts "<<<<< from yaml create translation for #{locale.code} : #{key} : #{pluralization_index}" unless RAILS_ENV['test'] | |
end | |
translation.value = value | |
translation.save! | |
end | |
def self.extract_i18n_keys(hash, parent_keys = []) | |
hash.inject([]) do |keys, (key, value)| | |
full_key = parent_keys + [key] | |
if value.is_a?(Hash) | |
# Nested hash | |
keys += extract_i18n_keys(value, full_key) | |
elsif value.present? | |
# String leaf node | |
keys << full_key.join(".") | |
end | |
keys | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment