Class: DolphinKit::BaiduService

Inherits:
Object
  • Object
show all
Defined in:
lib/dolphin_kit/services/baidu_service.rb

Constant Summary collapse

BASE_URL =
'https://fanyi-api.baidu.com/api/trans'

Instance Method Summary collapse

Constructor Details

#initialize(app_id: nil, app_key: nil, endpoint: nil) ⇒ BaiduService

Returns a new instance of BaiduService.



7
8
9
10
# File 'lib/dolphin_kit/services/baidu_service.rb', line 7

def initialize(app_id: nil, app_key: nil, endpoint: nil)
  @endpoint = "#{BASE_URL}/vip/translate"
  @app_id, @app_key = app_id, app_key
end

Instance Method Details

#call(text:, source: 'auto', target: nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/dolphin_kit/services/baidu_service.rb', line 12

def call(text:, source: 'auto', target: nil)
  target ||= (LANGUAGES.keys - [source.to_sym]).first

  params = { from: source, to: LANGUAGES[target.to_sym] }
  params.merge!(build_params(text))

  response = HTTP.post(@endpoint, form: params)
  result = JSON.parse(response.body)

  if (code = result['error_code'].to_i) > 52000
    @failure = FAILURES[code]
  else
    @failure = nil
  end

  result
end