class KepplerWatson::LanguageTraslator

Your code goes here…

Public Class Methods

new(params) click to toggle source
# File lib/keppler_watson/language_translator.rb, line 10
def initialize(params)
  @api_key = params[:api_key]
  @version = params[:version]
end

Public Instance Methods

identify(text) click to toggle source
# File lib/keppler_watson/language_translator.rb, line 20
def identify(text)
  api_post(:identify, text)
end
translate(text, model_id="es-en") click to toggle source
# File lib/keppler_watson/language_translator.rb, line 15
def translate(text, model_id="es-en")
  params = { text: text, model_id: model_id }
  api_post(:translate, params)
end

Private Instance Methods

api_post(action, params) click to toggle source
# File lib/keppler_watson/language_translator.rb, line 30
def api_post(action, params)
  uri = URI.parse("#{api_url}/#{action.to_s}?version=#{@version}")
  request = Net::HTTP::Post.new(uri)
  if action.eql?(:translate)
    request['Content-Type'] = "application/json"
    request.body = params.to_json
  else
    request['Content-Type'] = "text/plain"
    request.body = params.to_json
  end
  request.basic_auth("apikey", @api_key.to_s)
  req_options = { use_ssl: uri.scheme == "https", }
  response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
    http.request(request)
  end
  JSON.parse(response.body, object_class: OpenStruct)
end
api_url() click to toggle source
# File lib/keppler_watson/language_translator.rb, line 26
def api_url
  'https://gateway.watsonplatform.net/language-translator/api/v3'
end