1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  #
  # Shuffle locale YML files into 1 aggregate locale file
  # if anything bad happens, back out and revert to last created yml
  # http://www.tokumine.com/2010/07/16/using-split-locale-files-with-tolk/
  # Change en.yml to your base locale
  #
    desc "Merge en.yml file from separated translation files"
    task :merge_locales  => :environment do  
      unless ENV.include?("locale")
        raise "usage: rake locale= # Select a locale to merge. Must be a valid locale" 
      end
      locale = ENV['locale']     

      unless I18n.available_locales.include?(locale.to_sym)
        raise "Locale must be one of this:\n#{I18n.available_locales.join("\n")}" 
      end

      if I18n.default_locale==locale.to_sym
        raise "You can't merge default locale => #{locale.to_sym}"
      end      

      locale_yml = "#{locale}.yml"
      old_locale_yml = "#{locale}_old.yml"
      files = "#{locale}.{rb,yml}"
      locale_files = Dir[File.join(RAILS_ROOT, 'config', 'locales', '**', files)]    
      puts "locale_files => #{locale_files}"
      merge_file = File.join(RAILS_ROOT, 'config', 'locales', locale_yml)
      puts "\n\n merge_file => #{merge_file}"
      merge_file_old = File.join(RAILS_ROOT, 'config', 'locales', old_locale_yml)

      # move existing en.yml file to one side if it exists
      if FileTest.exists? merge_file
        FileUtils.mv merge_file, merge_file_old, :force => true
      end  

      begin      
        # aggregate the locales
        agg_locs = YAML.load_file(locale_files.pop)
        locale_files.each do |loc_yml|
          agg_locs[locale].merge! YAML.load_file(loc_yml)[locale]  # SEE IF WE CAN GET MERGE TO THROW EXCEPTION IF DUP
        end

        # write it back to a yml
        File.open( merge_file, 'w' ) do |out|
          YAML.dump( agg_locs, out )
        end      
      rescue Exception => e
        FileUtils.mv merge_file_old, merge_file, :force => true
      ensure
        FileUtils.rm merge_file_old, :force => true  
      end           

      # done?
      puts "linked all #{locale_files.size+1} locale files to #{merge_file}"
    end