Sha256: b0c8c31857fc87e90a9bbb511c05b72a6b7311cd10a089dcd87b8d8451d8dd93

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

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)
        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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tongues-0.0.12 lib/tongues/api_connexion.rb