class PryTranslator::Provider::Youdao

Public Class Methods

new() click to toggle source
# File lib/pry-translator/provider/youdao.rb, line 6
def initialize
  api_key_param = [:keyfrom, :key]
  api_href = 'http://fanyi.youdao.com/'

  super(api_href, api_key_param)
end

Public Instance Methods

format(hash) click to toggle source
# File lib/pry-translator/provider/youdao.rb, line 39
def format(hash)
  h = {}

  h['translation'] = hash['translation']
  h['explains']    = hash['basic']['explains'] if hash['basic']
  h['code']        = hash['errorCode']

  h
end
pretty_string(hash) click to toggle source
# File lib/pry-translator/provider/youdao.rb, line 31
def pretty_string(hash)
  hash = format(hash)
  str = hash['translation'].join(' ').colorize(:red)
  str << "\n#{PryTranslator::INDENT}" << hash['explains'].join("\n#{PryTranslator::INDENT}") if hash['explains']

  str
end
translate(text, args={}) click to toggle source
# File lib/pry-translator/provider/youdao.rb, line 13
def translate(text, args={})
  args['type']    = 'data'
  args['version'] = '1.1'
  args['doctype'] = 'json'
  args['q']       = text

  begin
    result = JSON.parse(get('/openapi.do', args))
    #result = format(result)
  rescue JSON::ParserError => e
    raise ProviderError.new('failed parsing response from youdao.')
  rescue
    raise e
  end

  pretty_string result
end