class I18n::Tasks::Translators::GoogleTranslator

Constants

SUPPORTED_LOCALES_WITH_REGION

Public Class Methods

new(*) click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 7
def initialize(*)
  begin
    require 'easy_translate'
  rescue LoadError
    raise ::I18n::Tasks::CommandError, "Add gem 'easy_translate' to your Gemfile to use this command"
  end
  super
end

Protected Instance Methods

no_results_error_message() click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 38
def no_results_error_message
  I18n.t('i18n_tasks.google_translate.errors.no_results')
end
options_for_html() click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 30
def options_for_html
  { html: true }
end
options_for_plain() click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 34
def options_for_plain
  { format: 'text' }
end
options_for_translate_values(from:, to:, **options) click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 22
def options_for_translate_values(from:, to:, **options)
  options.merge(
    api_key: api_key,
    from: to_google_translate_compatible_locale(from),
    to: to_google_translate_compatible_locale(to)
  )
end
translate_values(list, **options) click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 18
def translate_values(list, **options)
  EasyTranslate.translate(list, options)
end

Private Instance Methods

api_key() click to toggle source
# File lib/i18n/tasks/translators/google_translator.rb, line 53
def api_key
  @api_key ||= begin
    key = @i18n_tasks.translation_config[:google_translate_api_key]
    # fallback with deprecation warning
    if @i18n_tasks.translation_config[:api_key]
      @i18n_tasks.warn_deprecated(
        'Please rename Google Translate API Key from `api_key` to `google_translate_api_key`.'
      )
      key ||= translation_config[:api_key]
    end
    fail ::I18n::Tasks::CommandError, I18n.t('i18n_tasks.google_translate.errors.no_api_key') if key.blank?

    key
  end
end
to_google_translate_compatible_locale(locale) click to toggle source

Convert 'es-ES' to 'es'

# File lib/i18n/tasks/translators/google_translator.rb, line 47
def to_google_translate_compatible_locale(locale)
  return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale)

  locale.split('-', 2).first
end