Class: Translate
- Inherits:
-
Object
- Object
- Translate
- Defined in:
- lib/tolgee_liquid/translate.rb
Overview
A translator will try to get the translations, handle interpolations and convert it to static string. If it’s in development mode it will fetch translations from tolgee’s platform. Otherwise, it will use static translations provided by outside.
Instance Method Summary collapse
-
#execute(name, vars, opts) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/AbcSize.
-
#fetch_translation(dict, name) ⇒ Object
rubocop:enable Metrics/MethodLength, Metrics/AbcSize.
-
#initialize ⇒ Translate
constructor
A new instance of Translate.
-
#remote_dict(locale) ⇒ Object
rubocop:disable Metrics/MethodLength.
Constructor Details
#initialize ⇒ Translate
Returns a new instance of Translate.
10 11 12 13 14 |
# File 'lib/tolgee_liquid/translate.rb', line 10 def initialize @tolgee_api_url = TolgeeLiquid.configuration.api_url @tolgee_api_key = TolgeeLiquid.configuration.api_key @tolgee_project_id = TolgeeLiquid.configuration.project_id end |
Instance Method Details
#execute(name, vars, opts) ⇒ Object
rubocop:disable Metrics/MethodLength, Metrics/AbcSize
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/tolgee_liquid/translate.rb', line 17 def execute(name, vars, opts) locale = opts[:locale] dev_mode = opts[:mode] == 'development' static_data = opts[:static_data] dict = dev_mode ? remote_dict(locale.to_s) : static_data[locale.to_sym] value = fetch_translation(dict, name) return name if value.nil? translation = MessageFormat.new(value, locale.to_s).format(vars.transform_keys(&:to_sym)) if dev_mode = { k: name }.to_json = ZeroWidthCharacterEncoder.new.execute() "#{translation}#{}" else translation end end |
#fetch_translation(dict, name) ⇒ Object
rubocop:enable Metrics/MethodLength, Metrics/AbcSize
37 38 39 40 41 42 43 |
# File 'lib/tolgee_liquid/translate.rb', line 37 def fetch_translation(dict, name) name.split('.').reduce(dict) do |level, cur| return nil if level[cur].nil? level[cur] end end |
#remote_dict(locale) ⇒ Object
rubocop:disable Metrics/MethodLength
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/tolgee_liquid/translate.rb', line 46 def remote_dict(locale) @remote_dict ||= begin url = URI("#{@tolgee_api_url}/v2/projects/#{@tolgee_project_id}/translations/#{locale}") http = Net::HTTP.new(url.host, url.port) http.use_ssl = true if url.scheme == 'https' request = Net::HTTP::Get.new(url) request['Accept'] = 'application/json' request['X-API-Key'] = @tolgee_api_key response = http.request(request) JSON.parse(response.body)[locale] rescue StandardError {} end end |