Sha256: 358bb2552acfd23ccf48c2b20f1feb409359da3341364c569995118789a9ddd1

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

require "net/http"
require "google_translate_error"
require "json"
require "languages"

class GoogleTranslate
  include Languages

  attr_reader :from, :to, :text, :uri, :translated

  GOOGLE_TRANSLATE_URI = "https://translate.googleapis.com/translate_a/single".freeze

  def initialize params
    @from = get_source_language params
    @to = get_target_language params
    @text = get_text params
    @uri = URI GOOGLE_TRANSLATE_URI
  end

  def translate
    if @translated
      return @translated
    else
      res = make_request build_query(dt: "t")
      @translated = JSON.parse(res.body).flatten[0]
    end
  end

  private
  def get_source_language params
    params[:from] || "auto"
  end

  def get_target_language params
    stripped_target_language = params[:to].to_s.strip
    if full_language_name stripped_target_language
      stripped_target_language
    else
      raise GoogleTranslateError, "Target language is invalid"
    end
  end

  def get_text params
    stripped_text = params[:text].to_s.strip
    if stripped_text.empty?
      raise GoogleTranslateError, "Text can not empty"
    else
      stripped_text
    end
  end

  def build_query dt: "t"
    {
      client: "gtx",
      sl: @from,
      tl: @to,
      dt: dt,
      q: @text,
      le: "UTF-8",
      oe: "UTF-8"
    }
  end

  def make_request query
    uri.query = URI.encode_www_form query
    res = Net::HTTP.get_response uri
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
free_google_translate-0.1 lib/google_translate.rb