Class: BetterTranslate::DirectTranslator
- Inherits:
-
Object
- Object
- BetterTranslate::DirectTranslator
- Defined in:
- lib/better_translate/direct_translator.rb
Overview
Direct text translator for non-YAML workflows
Provides convenience methods for translating individual strings or batches without requiring YAML files. Useful for runtime translation needs.
Instance Attribute Summary collapse
-
#config ⇒ Configuration
readonly
Configuration object.
Instance Method Summary collapse
-
#initialize(config) ⇒ DirectTranslator
constructor
Initialize direct translator.
-
#translate(text, to:, language_name:) ⇒ String
Translate a single text string.
-
#translate_batch(texts, to:, language_name:, skip_errors: false) ⇒ Array<String, nil>
Translate multiple text strings.
Constructor Details
#initialize(config) ⇒ DirectTranslator
Initialize direct translator
39 40 41 42 43 44 45 |
# File 'lib/better_translate/direct_translator.rb', line 39 def initialize(config) @config = config # Validate provider is configured (minimal validation for DirectTranslator) raise ConfigurationError, "Provider must be configured" unless config.provider @provider = ProviderFactory.create(config.provider, config) end |
Instance Attribute Details
#config ⇒ Configuration (readonly)
Returns Configuration object.
29 30 31 |
# File 'lib/better_translate/direct_translator.rb', line 29 def config @config end |
Instance Method Details
#translate(text, to:, language_name:) ⇒ String
Translate a single text string
61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/better_translate/direct_translator.rb', line 61 def translate(text, to:, language_name:) Validator.validate_text!(text) target_lang_code = to.to_s Validator.validate_language_code!(target_lang_code) @provider.translate_text(text, target_lang_code, language_name) rescue ValidationError raise # Re-raise validation errors without wrapping rescue ApiError, StandardError => e raise TranslationError.new( "Failed to translate text: #{e.}", context: { text: text, target_lang: target_lang_code, original_error: e } ) end |
#translate_batch(texts, to:, language_name:, skip_errors: false) ⇒ Array<String, nil>
Translate multiple text strings
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
# File 'lib/better_translate/direct_translator.rb', line 105 def translate_batch(texts, to:, language_name:, skip_errors: false) raise ArgumentError, "texts must be an Array" unless texts.is_a?(Array) return [] if texts.empty? # Validate all texts first texts.each { |text| Validator.validate_text!(text) } target_lang_code = to.to_s Validator.validate_language_code!(target_lang_code) # Translate each text texts.map do |text| @provider.translate_text(text, target_lang_code, language_name) rescue ApiError, StandardError => e unless skip_errors raise TranslationError.new( "Failed to translate text: #{e.}", context: { text: text, target_lang: target_lang_code, original_error: e } ) end nil end end |