Sha256: 9403e2330ce45f96e5091d992e49817058e249832a6cf38d3926def41c0fb32f

Contents?: true

Size: 704 Bytes

Versions: 2

Compression:

Stored size: 704 Bytes

Contents

require 'open-uri'

module I18nModelsGeneratorModule
  class Translator
    def initialize(lang)
      @lang, @cache = lang, {}
    end

    def translate(word)
      return @cache[word] if @cache[word]
      begin
        w = CGI.escape ActiveSupport::Inflector.humanize(word)
        json = OpenURI.open_uri("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=#{w}&langpair=en%7C#{@lang}").read
        result = ActiveSupport::JSON.decode(json)
        result['responseStatus'] == 200 ? (@cache[word] = result['responseData']['translatedText']) : word
      rescue => e
        puts %Q[failed to translate "#{word}" into "#{@lang}" language.]
        word
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
amatsuda-i18n_generators-0.1.0 generators/i18n_models/lib/translator.rb
amatsuda-i18n_generators-0.2.0 generators/i18n_models/lib/translator.rb