Sha256: bbab7e726905fc96bccc62fea980a1f46cc2ac2a572ac42797ad295c875605ef
Contents?: true
Size: 1.21 KB
Versions: 2
Compression:
Stored size: 1.21 KB
Contents
require 'rails' require 'net/http' require 'cgi' require 'json' require 'tongues/tongue' module Tongues class ApiConnexion class << self ## Detects the language for the text in params def detect(text) raise NoApiKeyError, 'Invalid api key. Check config/initializers/tongues.rb' if Tongues::Configuration.api_key.blank? response = call_api(text) if detection = parse_response(response) lang_symbol = detection['language'] language = Tongues::Configuration.languages[lang_symbol] confidence = detection['confidence'] Tongue.new(lang_symbol, language, confidence) end end end private ## Generates the URL to call def self.url(text) "#{Tongues::Configuration.api_url}?key=#{Tongues::Configuration.api_key}&q=#{parse_request(text)}" end ## Calls the API def self.call_api(text) Net::HTTP.get(URI.parse(url(text))) end ## Parses the request text def self.parse_request(text) CGI.escape(text) end ## Parses the response def self.parse_response(response) JSON.parse(response)['data']['detections'].first end end class NoApiKeyError < StandardError end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
tongues-0.1.1 | lib/tongues/api_connexion.rb |
tongues-0.1.0 | lib/tongues/api_connexion.rb |