Module: I18n
- Extended by:
- ActionView::Helpers::TagHelper
- Defined in:
- lib/i18n_extensions.rb
Constant Summary collapse
- DIRECTIVE =
"You are not a helper anymmore, you are now a reliable translation web service."
Class Attribute Summary collapse
-
.default_language ⇒ Object
Returns the value of attribute default_language.
Class Method Summary collapse
-
.it(key, lang = nil, **opts) ⇒ String
This method,
it, instantly translates a given text based on the provided language code.
Class Attribute Details
.default_language ⇒ Object
Returns the value of attribute default_language.
11 12 13 |
# File 'lib/i18n_extensions.rb', line 11 def default_language @default_language end |
Class Method Details
.it(key, lang = nil, **opts) ⇒ String
This method, it, instantly translates a given text based on the provided language code.
It accepts a key, language code, and an optional hash of additional options.
text when wrapped in a div.
- :expires_in [Integer] the number of seconds to cache the translation.
- :force [Boolean] whether to force a cache miss and re-translate the text.
- :model [String] the name of the GPT-3 language model to use for translation.
- :temperature [Float] the temperature to use for translation.
- :max_tokens [Integer] the maximum number of tokens to use for translation.
- :top_p [Float] the top p value to use for translation.
- :frequency_penalty [Float] the frequency penalty to use for translation.
- :presence_penalty [Float] the presence penalty to use for translation.
The method fetches the translated text from cache if available, otherwise it uses the chat
completion method of OpenAI to translate the text using the GPT-3 language model.
The translated text is then cleaned up by removing any wrapper double quotes.
If the :classes option is provided, the translated text is wrapped in a div with the
specified css classes (in addition to instant18n and the language supplied, i.e. espanol).
Note that the language will be parameterized, so that Español becomes espanol.
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/i18n_extensions.rb', line 45 def self.it(key, lang=nil, **opts) lang = (lang || default_language || I18n.default_locale || "en").to_s opts && opts.symbolize_keys! Rails.cache.fetch(cache_key(key, lang, opts), expires_in: (opts[:expires_in] || 1.year) , force: (opts[:force] || false)) do if lang.casecmp(default_language.to_s || I18n.default_locale.to_s || "en").zero? key else chat(prompt % { key: key, lang: lang }, directive: DIRECTIVE, **opts) end end.then do |text| text = text.to_s.gsub(/^"+|"+$/, '') # remove wrapper double quotes if opts[:class].present? tag.div(text, class: "instant18n #{lang.parameterize} #{opts[:class]}") else text end end end |