to_lang is a Ruby library that adds language translation methods to strings, backed by the Google Translate API.
gem install to_lang.
To use to_lang, require the library, then call
ToLang.start with your Google Translate API key. At this point you will have access to all the new translation methods, which take the form
to_language, where “language” is the language you wish to translate to.
Google Translate attempts to detect the source language, but you can specify it explicitly by calling methods in the form
to_language_from_source_language, where “source_language” is the source language. These methods are generated dynamically and will not appear in a call to
String.new.methods until they have been called once. Strings will, however,
respond_to? these methods prior to their dynamic definition.
The dynamic methods are simply syntactic sugar for
String#translate, which you can use directly as well.
Load and initialize to_lang:
Translate some text to Spanish:
“Very cool gem!”.to_spanish
=> “Muy fresco joya!”
A case where the source language is ambiguous:
=> “a pie”
=> “un pastel”
=> “hola mundo”
“a pie”.translate(‘es’, :from => ‘en’)
=> “un pastel”
to_lang adds the following methods to strings. Each of these methods can be called with an explicit source language by appending
_to_source_language to the method name.
API documentation can be found at rubydoc.info.
- Add Unicode support for Ruby 1.8. to_lang currently works safely only under 1.9.
Feedback and Contributions
Feedback is greatly appreciated, as are patch contributions. Feel free to fork the project and send me a pull request.