Method: Tg::Tg#translate

Defined in:
lib/tg/tg.rb

#translate(text) ⇒ Object



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
# File 'lib/tg/tg.rb', line 13

def translate text
  highlight = %w{noun verb adverb adjective}

  lang = text.ascii_only? ? :en : :ge;

  json_response = Net::HTTP.get_response(api_server, api_uri(text, lang)).body

  # weird unicode pair \xC2\xAD (some sort of hyphen) fix
  json_response.force_encoding 'utf-8'
  json_response.gsub!(/\xC2\xAD/i, '')

  parsed = JSON.parse json_response, :symbolize_names => true

  parsed.each do |data|
    word, text = data[:Word], data[:Text]
    text = text.gsub(/\s+/, ' ').strip

    text.gsub!(/(#{highlight.join('|')})/) { $1.color :blue    }
    text.gsub!(/({\p{Word}+})/)            { $1.color :magenta }
    text.gsub!(/(\[.+\])/)                 { $1.color :yellow  }

    puts word.capitalize.color :green
    text = text.split(/\d\) ?/).drop_while {|t| t == '' }
    text.map! {|t| t.split(/; ?/) }

    text.each_with_index do |g, i|
      print "#{i + 1}) "
      g.each {|t| puts t }
    end

    puts
  end
end