class Googletrans::Translator
Constants
- HTTP_OR_HTTPS_RE
- LANGUAGES
Public Class Methods
new(argument = {})
click to toggle source
# File lib/googletrans/translator.rb, line 9 def initialize(argument = {}) @service_urls = argument[:service_urls] ||= ['translate.google.cn'] @user_agent = argument[:user_agent] ||= 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' @service_urls.map! { |e| (e =~ HTTP_OR_HTTPS_RE) ? e : "https://#{e}" } end
Public Instance Methods
translator(query,src='auto',dest)
click to toggle source
# File lib/googletrans/translator.rb, line 15 def translator query,src='auto',dest raise "src is wrong" unless LANGUAGES.include? src raise "dest is wrong" unless LANGUAGES.include? dest return query.map { |e| translator e,src,dest } if query.class == Array url = service_url token = Token.new(query,url).token response = token[:persistent].get "/translate_a/single",:params => build_params(query:query,src:src,dest:dest,token:token[:token]) raise "request failed" unless response.status.success? json = JSON.parse response.body.to_s translated = json&.first&.map { |e| e&.first }.join {query:query,translated:translated,src:json[2],dest:dest} end
Private Instance Methods
build_params(params = {})
click to toggle source
# File lib/googletrans/translator.rb, line 33 def build_params params = {} { 'client': 'webapp', 'sl': params[:src], 'tl': params[:dest], 'hl': params[:dest], 'dt': ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'], 'ie': 'UTF-8', 'oe': 'UTF-8', 'otf': 1, 'ssel': 0, 'tsel': 0, 'tk': params[:token], 'q': params[:query], } end
service_url()
click to toggle source
# File lib/googletrans/translator.rb, line 29 def service_url @service_urls.sample end