|
| 1 | +module Tolk |
| 2 | + module Sync |
| 3 | + def self.included(base) |
| 4 | + base.send :extend, ClassMethods |
| 5 | + end |
| 6 | + |
| 7 | + module ClassMethods |
| 8 | + def sync! |
| 9 | + raise "Primary locale is not set. Please set Locale.primary_locale_name in your application's config file" unless self.primary_locale_name |
| 10 | + |
| 11 | + translations = read_primary_locale_file |
| 12 | + sync_phrases(translations) |
| 13 | + end |
| 14 | + |
| 15 | + def read_primary_locale_file |
| 16 | + primary_file = "#{self.locales_config_path}/#{self.primary_locale_name}.yml" |
| 17 | + raise "Primary locale file #{primary_file} does not exists" unless File.exists?(primary_file) |
| 18 | + |
| 19 | + flat_hash(YAML::load(IO.read(primary_file))[self.primary_locale_name]) |
| 20 | + end |
| 21 | + |
| 22 | + private |
| 23 | + |
| 24 | + def sync_phrases(translations) |
| 25 | + primary_locale = self.primary_locale |
| 26 | + secondary_locales = self.secondary_locales |
| 27 | + |
| 28 | + # Handle deleted phrases |
| 29 | + translations.present? ? Phrase.destroy_all(["phrases.key NOT IN (?)", translations.keys]) : Phrase.destroy_all |
| 30 | + |
| 31 | + phrases = Phrase.all |
| 32 | + |
| 33 | + translations.each do |key, value| |
| 34 | + # Create phrase and primary translation if missing |
| 35 | + existing_phrase = phrases.detect {|p| p.key == key} || Phrase.create!(:key => key) |
| 36 | + translation = existing_phrase.translations.primary || primary_locale.translations.build(:phrase_id => existing_phrase.id) |
| 37 | + |
| 38 | + # Update primary translation if it's been changed |
| 39 | + if value.present? && translation.text != value |
| 40 | + translation.text = value |
| 41 | + translation.save! |
| 42 | + end |
| 43 | + |
| 44 | + # Make sure the translation record exists for all the locales |
| 45 | + # secondary_locales.each do |locale| |
| 46 | + # existing_translation = existing_phrase.translations.detect {|t| t.locale_id == locale.id } |
| 47 | + # locale.translations.create!(:phrase_id => existing_phrase.id) unless existing_translation |
| 48 | + # end |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + def flat_hash(data, prefix = '', result = {}) |
| 53 | + data.each do |key, value| |
| 54 | + current_prefix = prefix.present? ? "#{prefix}.#{key}" : key |
| 55 | + |
| 56 | + if value.is_a?(Hash) |
| 57 | + flat_hash(value, current_prefix, result) |
| 58 | + else |
| 59 | + result[current_prefix] = value |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + result |
| 64 | + end |
| 65 | + |
| 66 | + end |
| 67 | + |
| 68 | + end |
| 69 | +end |
0 commit comments