yat 0.0.4 → 0.5.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: c4e9cfdb16b8ab275ceff26d62dfcfb194862c84
4
- data.tar.gz: cb74a19f8be0afe8980dcafa991dab706b90ac4c
3
+ metadata.gz: fbcc2afae3d9016de309bd5c26b1febb13866b39
4
+ data.tar.gz: abe84701ed8d460ffc85045291566834a61072d6
5
5
  SHA512:
6
- metadata.gz: 8a6350dd4f6341b648dbdfb2bee403f87050bcb97f42db42b26a3aeb3cb7b8f79c2514c6c74d2597492df58e431f8d087e31b6dd6906113c4500094793b040cd
7
- data.tar.gz: 41abbaef831db0abe1f688807684703dc999e63c354fc67a2ea50c47dd28ecf90884c90bf57f1cad92a301307a236952136256f5bd9d5ecd6ebfd09d33fa3b52
6
+ metadata.gz: 20edee48855c245e26da299f55934097bb6ed3a6ffd0389eb7cfa06afc0f2fe163c96ecd9e7c4f2e7f9d926c7662e3d4a3336bd27a7bc55ba3f14562fdda9554
7
+ data.tar.gz: 1e60d5975dfb2419636611e01244108b7ba4690b929f52408f8a907a2b3e13baa75695c8c5e1a2584ef75cb3ef097f6686f7c26025b3b83f5f883a28ba809392
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
@@ -0,0 +1,7 @@
1
+ task :test, [:key] do |t, args|
2
+ if args.key.nil?
3
+ $stderr.puts "usage: rake test[<api_key>]" && exit
4
+ end
5
+
6
+ sh "TRANSLATOR_KEY=#{args.key} rspec test/*"
7
+ end
data/bin/yat CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env ruby
2
- require_relative "../lib/yat.rb"
3
-
2
+ require 'yat.rb'
4
3
  require 'yaml'
5
4
  require 'getoptlong'
6
5
 
@@ -10,6 +9,8 @@ $EXIT_OK = 0
10
9
  $EXIT_ECMDLINE = 3
11
10
  $EXIT_EFAIL = 4
12
11
 
12
+ # Celluloid.logger = nil
13
+
13
14
  def show_help
14
15
  print File.basename(__FILE__, '.rb')
15
16
  puts <<-HELP
@@ -30,7 +31,7 @@ def show_help
30
31
  -k KEY
31
32
 
32
33
  --make-config [FILE] generate YAML config
33
- -m [FILE] if FILE not given, but -c option provided, it's MissingArgument
34
+ -m [FILE] if FILE not given, but -c option provided, it's argument
34
35
  used instead
35
36
 
36
37
  --config FILE read in config from FILE
@@ -47,22 +48,9 @@ def show_help
47
48
 
48
49
  end
49
50
 
50
- def list_languages(translator, quiet, to_lang)
51
-
52
- res = translator.getLangs(ui: to_lang || 'en')
53
-
54
- unless quiet
55
- puts <<-EOF
56
-
57
- //====================\\\\
58
- ||Supported LANGUAGES ||
59
- \\\\====================//
60
-
61
- EOF
62
- end
63
-
51
+ def get_languages(translator, quiet, to_lang)
52
+ res = translator.get_languages(ui: to_lang || 'en')
64
53
  res["langs"].each { |short, long| puts "#{short}=>#{long} " }
65
- exit($EXIT_OK)
66
54
  end
67
55
 
68
56
  begin
@@ -84,7 +72,7 @@ begin
84
72
  config_file = nil
85
73
  new_config = nil
86
74
 
87
- opts.each { |opt, arg|
75
+ opts.each { |opt, arg|
88
76
  case opt
89
77
  when '--help'
90
78
  show_help
@@ -110,53 +98,44 @@ begin
110
98
  YandexTranslator.configuration.api_key = key unless key.nil?
111
99
  else
112
100
  YandexTranslator.configure.api_key = key
101
+
113
102
  end
103
+
104
+ raise GetoptLong::MissingArgument, "Please, specify api key" if YandexTranslator.configuration.api_key.nil?
114
105
 
115
106
  if make_config
116
107
  Dir.mkdir(new_config_dir) unless new_config.nil? || Dir.exist?(new_config_dir = File.dirname(new_config))
117
- new_config == '-' || new_config = config_file
108
+
109
+ new_config = config_file if new_config.nil? || new_config.empty?
110
+
118
111
  File.open(new_config || config_file, "w") { |file|
119
112
  file.write(YAML.dump(YandexTranslator.configuration))
120
113
  }
121
114
  end
122
115
 
123
- translator = YandexTranslator::JSONTranslator.new
124
-
125
- if list_languages
126
- list_languages(translator, quiet, to_lang)
127
- end
128
-
129
- if to_lang.nil?
116
+ if to_lang.nil? && !list_languages
130
117
  raise GetoptLong::MissingArgument, "Please, specify language for output"
131
118
  end
132
119
 
120
+ translator = YandexTranslator::Yat.new
121
+ if list_languages
122
+ get_languages(translator, quiet, to_lang)
123
+ exit($EXIT_OK)
124
+ end
125
+
133
126
  str = String.new
134
127
 
135
128
  ARGF.each_line do |line|
136
- while str.length + line.length > CHUNK_SIZE
137
- str, line = str + line[0, CHUNK_SIZE], line[CHUNK_SIZE - str.length, line.length]
138
- $stdout << translator.translate(text: str, lang: to_lang)
139
- str.clear
140
- end
141
- str += line
129
+ $stdout << translator.translate(text: line, lang: to_lang)["text"]
142
130
  end
143
- $stdout << translator.translate(text: str, lang: to_lang) unless str.empty?
144
131
 
145
- rescue GetoptLong::MissingArgument, GetoptLong::InvalidOption
146
- $stderr.puts
132
+ rescue GetoptLong::MissingArgument, GetoptLong::InvalidOption => exc
133
+ $stderr.puts exc.message
147
134
  show_help
148
135
  exit($EXIT_ECMDLINE)
149
136
 
150
- rescue YandexTranslator::ReturnCodeException => exc
151
- $stderr.puts "Error: #{exc.message}"
152
- exit($EXIT_EFAIL)
153
-
154
- rescue YandexTranslator::ApiFunctionNotSupported => exc
155
- $stderr.puts "Error: #{exc.message}"
156
- exit($EXIT_EFAIL)
157
-
158
- rescue YandexTranslator::NoApiKey => exc
159
- $stderr.puts "Error: #{exc.message}"
137
+ rescue Celluloid::TaskTerminated => exc
138
+ $stderr.puts "!Error: #{exc.message}"
160
139
  exit($EXIT_EFAIL)
161
140
 
162
141
  rescue Errno::ENOENT => exc
@@ -0,0 +1,14 @@
1
+ require 'json'
2
+
3
+ module YandexTranslator
4
+ class JSONParser
5
+ include Celluloid
6
+ include Celluloid::Notifications
7
+
8
+ def parse(text, index)
9
+ response = JSON.parse(text)
10
+ response["text"] = response["text"].inject {|elm, sum| elm + sum} if response["text"].is_a? Array
11
+ publish(:parsing_done, response, index)
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,40 @@
1
+ require 'rexml/document'
2
+
3
+ module YandexTranslator
4
+ class XMLParser
5
+ include Celluloid
6
+ include Celluloid::Notifications
7
+ include REXML
8
+
9
+ def parse(text, index)
10
+ xmldoc = REXML::Document.new(text)
11
+ response = Hash.new
12
+
13
+ if error = xmldoc.elements["Error"]
14
+ response["code"] = error.attributes['code'].to_i
15
+ response["message"] = error.attributes['message']
16
+ end
17
+
18
+ unless (element = xmldoc.elements["Langs/dirs"]).nil?
19
+ response["dirs"] = element.collect { |e|
20
+ e.text
21
+ }
22
+ end
23
+
24
+ unless (element = xmldoc.root.attributes["lang"]).nil?
25
+ response["lang"] = element
26
+ end
27
+ unless (element = xmldoc.elements["Langs/langs"]).nil?
28
+ response["langs"] = Hash.new
29
+ element.each { |e|
30
+ response["langs"][e.attributes["key"]] = e.attributes["value"]
31
+ }
32
+ end
33
+ unless (element = xmldoc.elements["Translation/text"]).nil?
34
+ response["text"] = element.text
35
+ end
36
+
37
+ publish(:parsing_done, response, index)
38
+ end
39
+ end
40
+ end
data/lib/yat.rb CHANGED
@@ -1,5 +1,129 @@
1
1
  TRANSLATOR_PATH = File.dirname(__FILE__) + "/yat/"
2
+ PARSER_PATH = File.dirname(__FILE__) + "/parsers/"
2
3
 
3
- ['generic', 'json', 'xml'].each { |f| require TRANSLATOR_PATH + "#{f}_translator" }
4
+ require TRANSLATOR_PATH + "medium"
4
5
  require TRANSLATOR_PATH + "config"
5
6
  require TRANSLATOR_PATH + "errors"
7
+ require TRANSLATOR_PATH + "connection"
8
+ require PARSER_PATH + "json_parser"
9
+ require PARSER_PATH + "xml_parser"
10
+
11
+ require 'celluloid/current'
12
+ require 'celluloid/logging'
13
+
14
+ module YandexTranslator
15
+ class Yat
16
+ include Celluloid
17
+ include Celluloid::Notifications
18
+ include Celluloid::Internals::Logger
19
+
20
+ finalizer :finalize
21
+ trap_exit :ambulance
22
+
23
+ def ambulance(actor, reason)
24
+ warn "#{actor.inspect} died because of #{reason.inspect}" unless reason.nil?
25
+ signal :return
26
+ end
27
+
28
+ def finalize
29
+ @parse_loop.terminate
30
+ @translator.terminate if @translator.alive?
31
+ end
32
+
33
+ def initialize(format = :json)
34
+ subscribe(:translator_ready, :__receive_responses)
35
+ subscribe(:parsing_done, :__return_responses)
36
+
37
+ @format = format
38
+ @responses_num = 0
39
+ @counter = 0
40
+ @translator = YandexTranslator::Medium.new_link
41
+ @parse_loop = self.async.parse_loop
42
+ end
43
+
44
+ def parse_loop
45
+ loop do
46
+ responses = wait :got_responses
47
+ responses.each.with_index { |response, index| parser.async.parse(response.body, index) }
48
+ end
49
+ end
50
+
51
+ def translate(params)
52
+ unless params[:text]
53
+ error "wrong or missing parameters: ':text'"
54
+ return nil
55
+ end
56
+ unless params[:lang]
57
+ error "wrong or missing parameters: ':lang'"
58
+ return nil
59
+ end
60
+
61
+ @result = []
62
+ @translator.async.translate(@format, params)
63
+ wait :return
64
+ res = Hash.new("")
65
+ res = @result.shift
66
+
67
+ if @result
68
+ @result.each do |hash|
69
+ res["text"] += hash["text"]
70
+ end
71
+ end
72
+ res
73
+ end
74
+
75
+ def get_languages(params = nil)
76
+ @result = []
77
+ params ||= Hash.new
78
+ @translator.async.getLangs(@format, params)
79
+ wait :return
80
+ @result.shift
81
+ end
82
+
83
+ def detect(params)
84
+ unless params[:text]
85
+ error "text parameter missing"
86
+ return nil
87
+ end
88
+
89
+ @result = []
90
+ @translator.async.detect(@format, params)
91
+ wait :return
92
+ @result = @result.shift if @result.size == 1
93
+ @result
94
+ end
95
+
96
+ def parser
97
+ case @format
98
+ when :json
99
+ JSONParser.new_link
100
+ when :xml
101
+ XMLParser.new_link
102
+ end
103
+ end
104
+
105
+ def __return_responses(topic, response, index)
106
+
107
+ if response["message"]
108
+ error response["message"]
109
+ @result.push nil
110
+ signal :return
111
+ return
112
+ end
113
+
114
+ @counter += 1
115
+ @result[index] = response
116
+
117
+ if @counter == @responses_num
118
+ @responses_num = @counter = 0
119
+ signal :return
120
+ end
121
+ end
122
+
123
+ def __receive_responses(topic, responses)
124
+ @responses_num = responses.length
125
+ signal :got_responses, responses
126
+ end
127
+
128
+ end
129
+ end
@@ -9,12 +9,15 @@ module YandexTranslator
9
9
  end
10
10
 
11
11
  class Configuration
12
- attr_accessor :api_key, :xml_path, :json_path
12
+ attr_accessor :api_key, :xml_path, :json_path, :host, :port, :chunk_size, :maximum_requests
13
13
 
14
14
  def initialize
15
+ @chunk_size = 10000
16
+ @maximum_requests = 10
15
17
  @api_key = nil
16
- @json_path = 'https://translate.yandex.net/api/v1.5/tr.json'
17
- @xml_path = 'https://translate.yandex.net/api/v1.5/tr'
18
+ @host = "https://translate.yandex.net"
19
+ @json_path = '/api/v1.5/tr.json'
20
+ @xml_path = '/api/v1.5/tr'
18
21
  end
19
22
  end
20
23
 
@@ -0,0 +1,29 @@
1
+ require 'net/http'
2
+ require 'celluloid/current'
3
+
4
+ module YandexTranslator
5
+
6
+ class Connection
7
+ include Celluloid
8
+ include Celluloid::Notifications
9
+
10
+ # finalizer :finalize
11
+
12
+ # def finalize
13
+ # p "connection dead!"
14
+ # end
15
+
16
+ def initialize
17
+ uri = URI(YandexTranslator::configuration.host)
18
+ @session = Net::HTTP.start(uri.host, uri.port,
19
+ :use_ssl => uri.scheme == 'https')
20
+ end
21
+
22
+ def request(uri, request_index, params = nil)
23
+ response = @session.request(Net::HTTP::Post.new(uri),
24
+ req = URI.encode_www_form(params || {}))
25
+
26
+ publish(:connection_response, request_index, response)
27
+ end
28
+ end
29
+ end
@@ -1,6 +1,4 @@
1
- # -*- encoding: utf-8 -*-
2
1
  module YandexTranslator
3
- class ReturnCodeException < Exception; end
4
- class ApiFunctionNotSupported < Exception; end
5
- class NoApiKey < Exception; end
2
+ class ReturnCodeException < StandardError; end
3
+ class NoApiKey < StandardError; end
6
4
  end
@@ -0,0 +1,79 @@
1
+ require 'celluloid/current'
2
+
3
+ module YandexTranslator
4
+ class Medium
5
+ include Celluloid
6
+ include Celluloid::Notifications
7
+
8
+ def initialize
9
+ subscribe(:connection_response, :stash_response)
10
+
11
+ @responses = Array.new
12
+ @response_num = 0
13
+ @request_index = 0
14
+ @request_max = YandexTranslator::configuration.maximum_requests
15
+ end
16
+
17
+ [:getLangs, :translate, :detect].each do |method|
18
+ define_method(method) do |format, params|
19
+
20
+ if params && params.has_key?(:text) && params[:text].length > 0
21
+ @request_estimate = (
22
+ Float(params[:text].length) /
23
+ YandexTranslator.configuration.chunk_size
24
+ ).ceil
25
+
26
+ split_input(params[:text]).each { |chunk|
27
+ params[:text] = chunk
28
+ request(__method__, format, params)
29
+ }
30
+ else
31
+ @request_estimate = 1
32
+ request(__method__, format, params)
33
+ end
34
+ end
35
+ end
36
+
37
+ def stash_response(topic, index, response)
38
+ signal :continue
39
+
40
+ @responses[index] = response
41
+ @response_num += 1
42
+
43
+ if @response_num == @request_estimate
44
+ publish(:translator_ready, @responses)
45
+ @request_index = @response_num = 0
46
+ end
47
+ end
48
+
49
+ protected
50
+ def request(function, format, params)
51
+ raise ArgumentError, "wrong format: #{format}" unless (YandexTranslator::configuration.instance_eval("#{format}_path") rescue nil)
52
+ raise NoApiKey, "provide api key" if (key = YandexTranslator::configuration.api_key).nil?
53
+
54
+ params[:key] = YandexTranslator::configuration.api_key
55
+
56
+ uri = URI(YandexTranslator::configuration.instance_eval("host + #{format}_path"))
57
+ uri.path += "/#{function}"
58
+
59
+ if @request_index - @response_num == @request_max
60
+ wait :continue
61
+ end
62
+
63
+ Connection.new_link.async.request(uri, @request_index, params)
64
+ @request_index += 1
65
+ end
66
+
67
+ def split_input(input)
68
+ str = String.new
69
+ chunks = Array.new
70
+ chunk_size = YandexTranslator::configuration.chunk_size
71
+ while str.length + input.length > chunk_size
72
+ str = input.slice!(0, chunk_size)
73
+ chunks << str.dup
74
+ str.clear
75
+ end
76
+ chunks << input.dup unless input.nil?
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,88 @@
1
+ require_relative '../lib/yat'
2
+ require 'celluloid/test'
3
+ require 'rspec'
4
+
5
+ raise "provide api key through env variable TRANSLATOR_KEY" if ENV['TRANSLATOR_KEY'].nil?
6
+
7
+ Celluloid.logger = nil
8
+ UNSUPPORTED_LANGUAGE = 'zz'
9
+
10
+ YandexTranslator::configure { |config|
11
+ config.api_key = ENV['TRANSLATOR_KEY']
12
+ }
13
+
14
+ shared_examples 'failures' do |translator_format|
15
+ around(:each) do |example|
16
+ Celluloid.boot
17
+ @translator = YandexTranslator::Yat.new(translator_format)
18
+ example.run
19
+ @translator.terminate
20
+ Celluloid.shutdown
21
+ end
22
+
23
+ it 'should fail on wrong api key' do
24
+ key = 'worng_api_key'
25
+ key, YandexTranslator::configuration.api_key = YandexTranslator::configuration.api_key, key
26
+
27
+ expect(@translator.get_languages).to be_nil
28
+ expect(@translator.detect(text: "test")).to be_nil
29
+ expect(@translator.translate(text: "test", lang: "ru")).to be_nil
30
+ YandexTranslator::configuration.api_key = key
31
+ end
32
+
33
+ it 'should fail on #detect call without :text specified' do
34
+ expect(@translator.detect({})).to be_nil
35
+ end
36
+
37
+ it 'should fail on #translate call without :text specified' do
38
+ expect(@translator.translate(lang: "ru")).to be_nil
39
+ end
40
+
41
+ it 'should fail on #translate call without :lang specified' do
42
+ expect(@translator.translate(text: "test text")).to be_nil
43
+ end
44
+
45
+ it 'should return error on #translate if unsupported language given' do
46
+ expect(@translator.translate(text: "test text",
47
+ lang: UNSUPPORTED_LANGUAGE)).to be_nil
48
+ end
49
+
50
+ end
51
+
52
+ shared_examples 'expected behavior' do |translator_format|
53
+ # around(:each) do |ex|
54
+ # Celluloid.boot
55
+ # @translator = YandexTranslator::Yat.new(translator_format)
56
+ # ex.run
57
+ # @translator.terminate
58
+ # Celluloid.shutdown
59
+ # end
60
+ it 'should return translation directions array' do
61
+ expect((@translator.get_languages["dirs"])).to_not be_empty
62
+ end
63
+
64
+ it 'should return translation directions array along with langs hash' do
65
+ expect(@translator.get_languages(ui: "ru")["langs"]).to_not be_empty
66
+ end
67
+
68
+ it 'should return lang on #detect' do
69
+ expect(@translator.detect(text: "test")["lang"]).to eq('en')
70
+ end
71
+
72
+ it "should return 'test text' on #translate" do
73
+ expect(@translator.translate(text: 'тестовый текст', lang: 'en')["text"]).to \
74
+ eq('test text')
75
+ end
76
+ end
77
+
78
+ describe "translator, xml format" do
79
+ translator_format = :xml
80
+ include_examples 'failures', translator_format
81
+ include_examples 'expected behavior', translator_format
82
+ end
83
+
84
+ describe "translator, json format" do
85
+ translator_format = :json
86
+ include_examples 'failures', translator_format
87
+ include_examples 'expected behavior', translator_format
88
+ end
metadata CHANGED
@@ -1,29 +1,61 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yat
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.4
4
+ version: 0.5.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - enoch0x5a
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-08-17 00:00:00.000000000 Z
12
- dependencies: []
13
- description: translates text files using yandex translator api
11
+ date: 2015-08-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: celluloid
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 0.17.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 0.17.0
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: 3.3.0
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: 3.3.0
41
+ description: translates using yandex translator api
14
42
  email:
15
43
  executables:
16
44
  - yat
17
45
  extensions: []
18
46
  extra_rdoc_files: []
19
47
  files:
48
+ - Gemfile
49
+ - Rakefile
20
50
  - bin/yat
51
+ - lib/parsers/json_parser.rb
52
+ - lib/parsers/xml_parser.rb
21
53
  - lib/yat.rb
22
54
  - lib/yat/config.rb
55
+ - lib/yat/connection.rb
23
56
  - lib/yat/errors.rb
24
- - lib/yat/generic_translator.rb
25
- - lib/yat/json_translator.rb
26
- - lib/yat/xml_translator.rb
57
+ - lib/yat/medium.rb
58
+ - test/yat_test.rb
27
59
  homepage:
28
60
  licenses:
29
61
  - MIT
@@ -48,4 +80,5 @@ rubygems_version: 2.4.5
48
80
  signing_key:
49
81
  specification_version: 4
50
82
  summary: yet another yandex translator
51
- test_files: []
83
+ test_files:
84
+ - test/yat_test.rb
@@ -1,65 +0,0 @@
1
- require 'net/http'
2
-
3
- module YandexTranslator
4
-
5
- class GenericTranslator
6
- attr_reader :response
7
-
8
- def initialize
9
- @response = nil
10
- end
11
-
12
- private
13
- def method_missing(api_function, *args)
14
- @response = make_request(api_function, *args)
15
-
16
- if @response.code == '404'
17
- raise YandexTranslator::ApiFunctionNotSupported, "#{api_function}"
18
- else
19
- GenericTranslator.send(:define_method, api_function) do |*args|
20
- make_request(__method__, *args)
21
- end
22
- end
23
- @response
24
- end
25
-
26
- protected
27
- def make_request(function, format, params = nil)
28
- raise ArgumentError, "wrong format: #{format}" if YandexTranslator::configuration.instance_eval("#{format}_path").nil?
29
-
30
- raise NoApiKey, "provide api key" if (key = YandexTranslator::configuration.api_key).nil?
31
-
32
- params[:key] = key
33
-
34
- uri = URI(YandexTranslator::configuration.instance_eval("#{format}_path"))
35
- uri.path += "/#{function}"
36
-
37
- Net::HTTP.start(uri.host, uri.port,
38
- :use_ssl => uri.scheme == 'https') do |https|
39
- request = Net::HTTP::Post.new(uri)
40
- @response = https.request(request, URI.encode_www_form(params))
41
- end
42
- end
43
-
44
- def error_check(return_code)
45
- unless return_code.nil? || return_code == 200
46
- raise YandexTranslator::ReturnCodeException, case return_code.to_i
47
- when 401
48
- "401: wrong api key"
49
- when 402
50
- "402: api key blocked"
51
- when 403
52
- "403: daily request limit exceeded"
53
- when 404
54
- "404: daily text volume limit exceeded"
55
- when 413
56
- "413: text size too big"
57
- when 422
58
- "422: unable to translate"
59
- when 501
60
- "501: translation direction is not supported"
61
- end
62
- end
63
- end
64
- end # class GenericTranslator
65
- end
@@ -1,33 +0,0 @@
1
- module YandexTranslator
2
- require 'json'
3
-
4
- class JSONTranslator < GenericTranslator
5
-
6
- def getLangs(params = nil)
7
- response = super(:json, params)
8
- response = JSON.parse(response.body)
9
- error_check(response["code"])
10
- response
11
- end
12
-
13
- def detect(params)
14
- raise ArgumentError, "text parameter not specified" unless params.has_key?(:text)
15
-
16
- response = super(:json, params)
17
- response = JSON.parse(response.body)
18
- error_check(response["code"])
19
- response["lang"]
20
- end
21
-
22
- def translate(params)
23
- raise ArgumentError, "text parameter not specified" unless params.has_key?(:text)
24
- raise ArgumentError, "lang parameter not specified" unless params.has_key?(:lang)
25
-
26
- response = super(:json, params)
27
- response = JSON.parse(response.body)
28
- error_check(response["code"])
29
- return response["text"].inject {|elm, sum| elm + sum} if response["text"].is_a? Array
30
- response["text"]
31
- end
32
- end
33
- end
@@ -1,59 +0,0 @@
1
- module YandexTranslator
2
- require 'rexml/document'
3
- include REXML
4
-
5
- class XMLTranslator < GenericTranslator
6
-
7
- def getLangs(params = nil)
8
-
9
- response = super(:xml, params)
10
-
11
- xmldoc = REXML::Document.new(response.body)
12
-
13
- if error = xmldoc.elements["Error"]
14
- error_check(error.attributes['code'])
15
- end
16
-
17
- response = Hash.new
18
- response["dirs"] = xmldoc.elements["Langs/dirs"].collect { |e|
19
- e.text
20
- }
21
- unless (langs = xmldoc.elements["Langs/langs"]).nil?
22
- response["langs"] = Hash.new
23
- langs.each {|e|
24
- response["langs"][e.attributes["key"]] = e.attributes["value"]
25
- }
26
- end
27
- response
28
- end
29
-
30
- def detect(params)
31
-
32
- raise ArgumentError, "text parameter not specified" unless params.has_key?(:text)
33
-
34
- response = super(:xml, params)
35
- xmldoc = REXML::Document.new(response.body)
36
-
37
- if error = xmldoc.elements["Error"]
38
- error_check(error.attributes['code'])
39
- end
40
-
41
- xmldoc.root.attributes["lang"]
42
- end
43
-
44
- def translate(params)
45
-
46
- raise ArgumentError, "text parameter not specified" unless params.has_key?(:text)
47
- raise ArgumentError, "lang parameter not specified" unless params.has_key?(:lang)
48
-
49
- response = super(:xml, params)
50
- xmldoc = REXML::Document.new(response.body)
51
-
52
- if error = xmldoc.elements["Error"]
53
- error_check(error.attributes['code'])
54
- end
55
-
56
- xmldoc.elements["Translation/text"].text
57
- end
58
- end # class XMLTranslator
59
- end