Class: C3po::Translator::Google

Inherits:
Object
  • Object
show all
Defined in:
lib/c3po/translator/google.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(to_be_translated = nil) ⇒ Google

Returns a new instance of Google.



9
10
11
12
13
14
# File 'lib/c3po/translator/google.rb', line 9

def initialize(to_be_translated = nil)
  @to_be_translated = to_be_translated
  @default = {
    :key => C3po::Translator::Configuration.google_api_key
  }
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



7
8
9
# File 'lib/c3po/translator/google.rb', line 7

def base_url
  @base_url
end

Instance Method Details

#build_detect_queryHash

Build a query for detect method of Google Translate api.

Examples:

build_detect_query

Returns:

  • (Hash)

    Hash of param.

Since:

  • 0.0.1



59
60
61
62
# File 'lib/c3po/translator/google.rb', line 59

def build_detect_query
  @base_url = 'https://www.googleapis.com/language/translate/v2/detect'
  @default.merge({:q => @to_be_translated})
end

#build_languages_queryHash

Build a query for languages method of Google Translate api.

Examples:

build_languages_query

Returns:

  • (Hash)

    Hash of param.

Since:

  • 0.0.1



45
46
47
48
# File 'lib/c3po/translator/google.rb', line 45

def build_languages_query
  @base_url = 'https://www.googleapis.com/language/translate/v2/languages'
  @default
end

#build_query(from, to) ⇒ Hash

Build a query for Google Translate api.

Examples:

build_query :fr, :en

Parameters:

  • Language (Symbol)

    to be translated from.

    Symbol

    Language to be translated to.

Returns:

  • (Hash)

    Hash of param.

Since:

  • 0.0.1



28
29
30
31
32
33
34
# File 'lib/c3po/translator/google.rb', line 28

def build_query(from, to)
  @base_url = 'https://www.googleapis.com/language/translate/v2'
  @default.merge({:q => @to_be_translated,
                  :source => from.to_s,
                  :target => to.to_s
                })
end

#parse(response) ⇒ String, Array

Parse json response from Google webservice.

Examples:

parse my_json

Parameters:

  • response (String)

    Json representation

Returns:

  • (String)

    Translated string.

  • (String)

    Detected language.

  • (Array)

    Languages list.

Since:

  • 0.0.1



77
78
79
80
81
82
83
84
85
86
# File 'lib/c3po/translator/google.rb', line 77

def parse(response)
  data = Yajl::Parser.parse(response)['data']
  if data['translations']
    data['translations'][0]['translatedText']
  elsif data['detections']
    data['detections'][0][0]["language"]
  else
    data['languages'].inject([]) {|languages, value| languages << value['language']}
  end
end