Friday, April 5, 2013

Using Rails’ New I18n Support in Real Life: Part the Fourth


December 16th, 2008 By: Daniel

So after tediously going through your entire site and extracting all displayed strings to a separate translation file, how do you know you didn’t miss something somewhere? My solution was to create a quick rake task that machine translates my English yaml file to something else. A quick sudo aptitude install bsdgames and I had pig latin at my fingertips. So I switched to that and browsed through the site and looked for anything that hadn’t changed. And I found quite a bit of stuff that I had missed.
# lib/tasks/pig.rake
desc "Creates a config/locales/pig-US.yml from config/locales/en-US.yml"
task :pig => :environment do
  DEFAULT_LOCALE = 'en-US'
  File.open(File.join(RAILS_ROOT, 'config', 'locales', 'pig-US.yml'), "w") do |fout|
    File.readlines(File.join(RAILS_ROOT, 'config', 'locales', "#{DEFAULT_LOCALE}.yml")).each do |line|
      unless line =~ /"/
        fout.puts line.sub(DEFAULT_LOCALE, 'pig-US')
      else
        key, *translation = line.split(':')
        translation = translation.join(':')
        translation.split(/(".*?")/).each do |quote|
          if quote =~ /"/
            quote.gsub!('"', '')
            string = quote.split(/(\{\{.*?\}\})/).map do |s|
              (s =~ /\{\{/) ? s : `echo "#{s.gsub('$', '\$')}" | pig`.chomp
            end
            translation.sub!(quote, string.join)
          end
        end
        fout.puts "#{key}:#{translation}"
      end
    end
  end
end
P.S. Note to anyone that actually tries to use this: This is just a quick and dirty script and will probably require some modification to work in your situation. In particular it requires all the strings you want translated to be within double quotes.

No comments:

Post a Comment