Module: Konjac::Translator

Defined in:
lib/konjac/translator.rb

Overview

A class consisting of functions for translation

Constant Summary collapse

DIFF_ADD =

A regex to identify whether the specific line in a diff file is an add line

/^\+(?!\+\+ )/

Class Method Summary collapse

Class Method Details

.load_dictionary(from_lang, to_lang, opts) ⇒ Object

Loads the parsed contents of a dictionary into the translator



65
66
67
# File 'lib/konjac/translator.rb', line 65

def load_dictionary(from_lang, to_lang, opts)
  @pairs = Dictionary.load(from_lang, to_lang, opts)
end

.translate_content(content) ⇒ Object

Translates content according to the current dictionaries and to/from languages



55
56
57
58
59
60
61
62
# File 'lib/konjac/translator.rb', line 55

def translate_content(content)
  @pairs.each do |pair|
    search, replace = pair
    content.gsub! search, replace
  end

  content
end

.translate_files(files, from_lang, to_lang, opts = {}) ⇒ Object

Translates a file or list of files

path = Dir[File.expand_path("~/.konjac/test_en.txt")]
Translator.translate_files path, :en, :ja, :using => [:dict]


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
# File 'lib/konjac/translator.rb', line 14

def translate_files(files, from_lang, to_lang, opts = {})
  load_dictionary from_lang, to_lang, opts
  
  files.each do |source|
    # Handle .diff files differently (har har)
    is_diff = (File.extname(source) == ".diff")

    temp_file = Tempfile.new("konjac")
    File.open(source, "r") do |file|
      file.each_line do |line|
        if is_diff && line !~ DIFF_ADD
          temp_file.puts line
        else
          temp_file.puts translate_content(line)
        end
      end
    end

    # Set output file
    if opts[:output].nil?
      target = source
    else
      target = File.expand_path(opts[:output])
    end

    if Utils.user_allows_overwrite?(target, opts)
      FileUtils.mv temp_file.path, target
    end
  end
end

.translate_word(word, from_lang, to_lang, opts = {}) ⇒ Object

Loads the dictionary, then translates a word or phrase from the specified language into another language



47
48
49
50
51
# File 'lib/konjac/translator.rb', line 47

def translate_word(word, from_lang, to_lang, opts = {})
  load_dictionary from_lang, to_lang, opts

  translate_content word
end