Module: Yandex::API::Translate

Defined in:
lib/yandex-api/translate.rb

Constant Summary collapse

URL_API =
'https://translate.yandex.net/'

Class Method Summary collapse

Class Method Details

.configurationObject



13
14
15
16
17
18
19
20
# File 'lib/yandex-api/translate.rb', line 13

def self.configuration
  if defined? @environment
    raise RuntimeError.new("not configured Yandex.Translate for #{@environment} enviroment") unless @configuration
  else
    raise RuntimeError.new('not configured Yandex.Translate') unless @configuration
  end
  @configuration
end

.connectionObject



36
37
38
39
40
41
42
43
44
45
# File 'lib/yandex-api/translate.rb', line 36

def self.connection
  return @connection if defined? @connection
  uri = URI.parse(URL_API)
  @connection = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == "https"
    @connection.use_ssl = true
    @connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  return @connection
end

.detect(text) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/yandex-api/translate.rb', line 74

def self.detect(text)
  result = request(:detect, :text => text)
  if result.include? 'lang'
    return result['lang']
  else
    raise RuntimeError.new "#{json['code']} - Can't detect language"
  end
end

.do(text, lang, options = {}) ⇒ Object



83
84
85
86
87
88
# File 'lib/yandex-api/translate.rb', line 83

def self.do(text, lang, options = {})
  request(:translate, options.merge({
    :text => text,
    :lang => lang
  }))
end

.languagesObject



70
71
72
# File 'lib/yandex-api/translate.rb', line 70

def self.languages
  request(:getLangs)
end

.load(file, env = nil) ⇒ Object



22
23
24
25
26
# File 'lib/yandex-api/translate.rb', line 22

def self.load file, env = nil
  @environment = env.to_s if env
  config = YAML.load_file(file)
  @configuration = defined?(@environment) ? config[@environment] : config
end

.parse_json(json) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/yandex-api/translate.rb', line 28

def self.parse_json json
  begin
    return JSON.parse(json)
  rescue => e
    raise RuntimeError.new "#{e.message} in response"
  end
end

.request(path, params = {}) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/yandex-api/translate.rb', line 47

def self.request path, params = {}

  if configuration['verbose']
    puts "\t\033[32mYandex.Translate:\033[0m #{params}"
  end

  query = (
    params.merge!({
      :key => configuration['token'],
      :ui => configuration['ui']
    })
  ).collect {|key,value| "#{key.to_s}=#{CGI.escape(value.to_s)}" }.join("&")

  response = connection.send(:get,[File.join('/api/v1.5/tr.json',path.to_s),query].join("?"))

  json = Direct.parse_json(response.body)

  if json.has_key?('code') and json.has_key?('message')
    raise RuntimeError.new "#{json['code']} - #{json['message']}"
  end
  return json
end