Class: Reverso::Translator
- Inherits:
-
Object
- Object
- Reverso::Translator
- Defined in:
- lib/reverso/translator.rb
Class Method Summary collapse
-
.translate(phrase, params = {}) ⇒ Object
Returns translated
phrase
.
Instance Method Summary collapse
-
#initialize ⇒ Translator
constructor
:nodoc:.
- #query_service(phrase, params) ⇒ Object
- #query_string(phrase, direction) ⇒ Object
- #response ⇒ Object
- #result ⇒ Object
-
#translate(phrase, params) ⇒ Object
:enddoc:.
- #translation_code(params) ⇒ Object
Constructor Details
#initialize ⇒ Translator
:nodoc:
57 58 59 |
# File 'lib/reverso/translator.rb', line 57 def initialize # :nodoc: @http = Net::HTTP.new(SERVICE_HOST) end |
Class Method Details
.translate(phrase, params = {}) ⇒ Object
Returns translated phrase
params
must contain following values:
:from source language name
:to destination language name
It is possible to use short language names.
#–
params
may contain following options:
:hack_auth set to non false value if you need translate big piece of text
20 21 22 |
# File 'lib/reverso/translator.rb', line 20 def self.translate(phrase, params = {}) new.translate(phrase, params) end |
Instance Method Details
#query_service(phrase, params) ⇒ Object
30 31 32 33 34 |
# File 'lib/reverso/translator.rb', line 30 def query_service(phrase, params) @response = @http.post(SERVICE_PATH, query_string(phrase, translation_code(params)), (params[:hack_auth] ? HEADERS.merge(HACK_HEADERS) : HEADERS)) end |
#query_string(phrase, direction) ⇒ Object
53 54 55 |
# File 'lib/reverso/translator.rb', line 53 def query_string(phrase, direction) JSON(:searchText => phrase, :direction => direction) end |
#response ⇒ Object
36 37 38 |
# File 'lib/reverso/translator.rb', line 36 def response JSON.parse @response.body end |
#result ⇒ Object
40 41 42 |
# File 'lib/reverso/translator.rb', line 40 def result response['d']['result'] end |
#translate(phrase, params) ⇒ Object
:enddoc:
25 26 27 28 |
# File 'lib/reverso/translator.rb', line 25 def translate(phrase, params) query_service(phrase, params) result end |
#translation_code(params) ⇒ Object
44 45 46 47 48 49 50 51 |
# File 'lib/reverso/translator.rb', line 44 def translation_code(params) if from_pack = TRANSLATION_CODES.detect { |from, pack| from =~ /^#{params[:from]}/i } and direction = from_pack[1].detect { |to, code| to =~ /^#{params[:to]}/i } direction[1] else raise 'Unable to perform translation.' end end |