Google Translate Gem

Gem

1
  gem 'google-cloud-translate'

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

Bundle

1
  bundle

Make sure to run bundle in terminal.

Create Module

1
  touch lib/google_translate.rb

Add a new file to your lib folder.

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require "google/cloud/translate"
module GoogleTranslate
      def self.translate_text(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

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

‘hola’ was correctly translated to ‘hello’.

-dvcv