Class: Translator
- Inherits:
-
Object
- Object
- Translator
- Defined in:
- lib/translator.rb
Constant Summary collapse
- Site_Url =
'ajax.googleapis.com'
- Request_Uri =
"/ajax/services/language/translate"
- SUPPORTED_LANG_CODES =
['sr','lt','lv','iw','cy','ga','id','de','zh-TW','es','sl','ko','it','eu','az','af','sk','pt-PT','no','gl','bg','ar','tr','fa','mk','el','da','yi','ur','uk','ro','ja','zh','sw','mt','ms','is','ka','en','hr','ca','th','ru','hy','vi','tl','sv','hu','hi','fi','sq','pl','fr','et','nl','cs','zh-CN','be']
Instance Method Summary collapse
-
#to_en(text) ⇒ Object
added in 0.1.2 to support from unknown to english.
- #translate(text, to, from = 'en') ⇒ Object
Instance Method Details
#to_en(text) ⇒ Object
added in 0.1.2 to support from unknown to english
48 49 50 |
# File 'lib/translator.rb', line 48 def to_en(text) translate( text, "en", "" ) end |
#translate(text, to, from = 'en') ⇒ Object
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/translator.rb', line 17 def translate( text, to, from='en' ) begin raise UnSupportedLanguage unless SUPPORTED_LANG_CODES.include?(to) raise UnSupportedLanguage unless SUPPORTED_LANG_CODES.include?(from) unless from.empty? # letting to translate from unknown language http = Net::HTTP.new(Site_Url, 80) request = Net::HTTP::Post.new(Request_Uri) request.set_form_data({'v'=>1.0, 'langpair'=>"#{from}|#{to}", 'q'=>"#{text}"}) response = http.request(request) json_response_body = JSON.parse( response.body ) if json_response_body['responseStatus'] == 200 json_response_body['responseData']['translatedText'] else puts json_response_body['responseDetails'] raise StandardError, response['responseDetails'] end rescue UnSupportedLanguage raise UnSupportedLanguage.new rescue => err_msg puts "#{err_msg}" end end |