module Autolang
Constants
- VERSION
Public Class Methods
translate(text, language)
click to toggle source
# File lib/autolang.rb, line 5 def translate(text, language) e = TranslationEscaper.new(text) e.unescape EasyTranslate.translate(e.escaped, :to => language, :format => 'html') end
translate_into_new_language(key, file, language)
click to toggle source
# File lib/autolang.rb, line 10 def translate_into_new_language(key, file, language) EasyTranslate.api_key = key if file.end_with?(".json") translate_json_into_new_file(file, language) else translate_gettext_into_new_file(file, language) end end
Private Class Methods
extract_msgid(text)
click to toggle source
# File lib/autolang.rb, line 21 def extract_msgid(text) return unless text =~ /^msgid/ return unless msgid = text.scan(/"(.+)"/)[0] msgid.first.to_s.gsub(' | ','|') end
translate_gettext_into_new_file(pot_file, language)
click to toggle source
# File lib/autolang.rb, line 27 def translate_gettext_into_new_file(pot_file, language) po_file = File.join(File.dirname(pot_file), language, "#{language}.po") # create directory if it does not exist language_dir = File.dirname(po_file) unless FileTest.exist?(language_dir) puts "Creating new language directory: #{language_dir}" Dir.mkdir(language_dir) end # generate po file if it does not exist unless FileTest.exist?(po_file) if system("which msginit") puts "Generating new language file: #{po_file}" `msginit -i #{pot_file} -o #{po_file} -l #{language} --no-translator` else warn "msginit not available creating new language by copying" `cp #{pot_file} #{po_file}` end raise "Error during initialization" unless $?.success? end lines = translate_po_file_content(File.readlines(po_file), language) File.open(po_file, "w+") { |f| f.write(lines*"\n") } end
translate_hash(hash, language)
click to toggle source
# File lib/autolang.rb, line 61 def translate_hash(hash, language) hash.inject({}) do |all, (k,v)| all[k] = if v.is_a?(String) translate(v, language) elsif v.is_a?(Hash) translate_hash(v, language) else v end all end end
translate_json_into_new_file(file, language)
click to toggle source
# File lib/autolang.rb, line 53 def translate_json_into_new_file(file, language) require 'json' out = File.join(File.dirname(file), "#{language}.json") old = JSON.load(File.read(file)) new = translate_hash(old, language) File.open(out, "w+") { |f| f.write(JSON.dump(new)) } end
translate_po_file_content(lines, language)
click to toggle source
# File lib/autolang.rb, line 74 def translate_po_file_content(lines, language) msgstr = "" puts "Translating..." lines.map do |line| #read string to translate if msgid = extract_msgid(line) msgstr = translate(msgid, language) puts msgid puts msgstr puts '-'*80 #replace translation elsif line =~ /^msgstr/ and not msgstr.empty? line = "msgstr \"#{msgstr}\"" end line.strip end end