Sha256: f62727964df5239f8edbcbff4727d78d5f5957a13930a895c0a69f9275ddbd59

Contents?: true

Size: 1.75 KB

Versions: 1

Compression:

Stored size: 1.75 KB

Contents

module LocaleApp
  class Updater

    def update(data)
      data['locales'].each do |short_code|
        filename = File.join(LocaleApp.configuration.translation_data_directory, "#{short_code}.yml")

        if File.exist?(filename)
          translations = YAML.load(File.read(filename))
          if data['translations'] && data['translations'][short_code]
            new_data = { short_code => data['translations'][short_code] }
            translations.deep_merge!(new_data)
          end
        else
          translations = { short_code => data['translations'][short_code] }
        end

        if data['deleted']
          data['deleted'].each do |key|
            remove_flattened_key!(translations, short_code, key)
          end
        end

        if translations[short_code]
          atomic_write(filename) do |file|
            file.write translations.ya2yaml[5..-1]
          end
        end
      end
    end

    private
    def remove_flattened_key!(hash, locale, key)
      keys = I18n.normalize_keys(locale, key, '').map(&:to_s)
      current_key = keys.shift
      remove_child_keys!(hash[current_key], keys)
      hash
    end

    def remove_child_keys!(sub_hash, keys)
      current_key = keys.shift
      if keys.empty?
        sub_hash.delete(current_key)
      else
        child_hash = sub_hash[current_key]
        unless child_hash.nil?
          remove_child_keys!(child_hash, keys)
          if child_hash.empty?
            sub_hash.delete(current_key)
          end
        end
      end
    end

    # from ActiveSupport
    def atomic_write(file_name, temp_dir = Dir.tmpdir)
      temp_file = Tempfile.new(File.basename(file_name), temp_dir)
      yield temp_file
      temp_file.close
      File.rename(temp_file.path, file_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
localeapp-0.0.7 lib/locale_app/updater.rb