Class: Linguo::Detect

Inherits:
Object
  • Object
show all
Defined in:
lib/linguo/detect.rb

Constant Summary collapse

API_URL =

The URL to the API endpoint.

'http://ws.detectlanguage.com/0.2/detect'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, api_key) ⇒ Linguo::Detect

Initializes a new Detect object and parses the API response.

Parameters:

  • text (String)

    The text required to detect.

  • api_key (String)

    The API key obtained from detectlanguage.com.

Raises:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/linguo/detect.rb', line 14

def initialize(text, api_key)
  raise Errors::MissingApiKey, "No API key provided." unless api_key

  uri = URI API_URL
  req = Net::HTTP::Post.new(uri.path)
  req.set_form_data('q' => text, 'key' => api_key)
  res = Net::HTTP.start(uri.hostname, uri.port) {|http| http.request(req)}

  if res.code.to_i == 200
    data = JSON.parse(res.body)
    raise Errors::ApiError, data['error']['message'] if data['error']
    raise Errors::UnexpectedApiException if data['data'].nil?
    @detections = data['data']['detections']
  else
    raise Errors::ApiConnectionError, "#{response.code} #{response.message}"
  end
end

Instance Attribute Details

#detectionsObject (readonly)

An array of detections.



7
8
9
# File 'lib/linguo/detect.rb', line 7

def detections
  @detections
end