Google Translate Gem

Gem

gem 'google-cloud-translate'

Like many other rails apps the first thing to do is to include the google translate gem.

Bundle

bundle

Make sure to run bundle in terminal.

Create Module

touch lib/google_translate.rb

Add a new file to your lib folder.

The Code

require "google/cloud/translate
module GoogleTranslate
 def self.translatetext(text, to = 'en')
  begin
   translate = Google::Cloud::Translate.new project: PROJECT
ID, key: API_KEY
   translation = translate.translate text, to: to
   return translation.text
  rescue Google::Cloud::Error => e
   puts e.message
  end
  puts "Text was not translated correctly. Returning original text"
  text
 end
end

Add the following to your new file. You will need to replace PROJECT_ID and API_KEY with your very own authentication.

The Output

rails c
[1] pry(main)> GoogleTranslate.translate_text('hola')
=> "Hello"

'hola' was correctly translated to 'hello'.

-dvcv