Google Translate Gem


gem 'google-cloud-translate'

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



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')
   translate = project: PROJECT
ID, key: API_KEY
   translation = translate.translate text, to: to
   return translation.text
  rescue Google::Cloud::Error => e
   puts e.message
  puts "Text was not translated correctly. Returning original text"

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'.