Class: Tml::Language

Inherits:
Base
  • Object
show all
Defined in:
lib/tml/language.rb

Overview

– Copyright © 2017 Translation Exchange, Inc

_______                  _       _   _             ______          _

|__ __| | | | | (_) | __| | |

| |_ __ __ _ _ __  ___| | __ _| |_ _  ___  _ __ | |__  __  _____| |__   __ _ _ __   __ _  ___
| | '__/ _` | '_ \/ __| |/ _` | __| |/ _ \| '_ \|  __| \ \/ / __| '_ \ / _` | '_ \ / _` |/ _ \
| | | | (_| | | | \__ \ | (_| | |_| | (_) | | | | |____ >  < (__| | | | (_| | | | | (_| |  __/
|_|_|  \__,_|_| |_|___/_|\__,_|\__|_|\___/|_| |_|______/_/\_\___|_| |_|\__,_|_| |_|\__, |\___|
                                                                                    __/ |
                                                                                   |___/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ++

Instance Attribute Summary

Attributes inherited from Base

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

attributes, belongs_to, has_many, hash_value, #hash_value, #initialize, #method_missing, #to_hash

Constructor Details

This class inherits a constructor from Tml::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Tml::Base

Class Method Details

.cache_key(locale) ⇒ Object

Returns language cache key



39
40
41
# File 'lib/tml/language.rb', line 39

def self.cache_key(locale)
  File.join(locale, 'language')
end

.normalize_locale(locale) ⇒ Object

Supported locales must be of a form en, en-US, az-Cyrl-AZ



44
45
46
47
48
49
# File 'lib/tml/language.rb', line 44

def self.normalize_locale(locale)
  parts = locale.split(/[-_]/)
  return parts.first.downcase if parts.size == 1
  return [parts.first.downcase, parts.last.upcase].join('-') if parts.size == 2
  ([parts.first.downcase] + parts[1..-2].collect{|part| part.downcase.capitalize} + [parts.first.upcase]).join('-')
end

Instance Method Details

#align(dest) ⇒ Object



110
111
112
113
# File 'lib/tml/language.rb', line 110

def align(dest)
  return dest unless right_to_left?
  dest.to_s == 'left' ? 'right' : 'left'
end

#case_by_keyword(keyword) ⇒ Object



93
94
95
# File 'lib/tml/language.rb', line 93

def case_by_keyword(keyword)
  cases[keyword]
end

#context_by_keyword(keyword) ⇒ Object

Returns context by keyword



84
85
86
# File 'lib/tml/language.rb', line 84

def context_by_keyword(keyword)
  hash_value(contexts, keyword)
end

#context_by_token_name(token_name) ⇒ Object

Returns context by token name



89
90
91
# File 'lib/tml/language.rb', line 89

def context_by_token_name(token_name)
  contexts.values.detect{|ctx| ctx.applies_to_token?(token_name)}
end

#current_source(options) ⇒ Object



120
121
122
123
# File 'lib/tml/language.rb', line 120

def current_source(options)
  return options[:source] if options and options[:source]
  (Tml.session.block_option(:source) || Tml.session.current_source || 'undefined').to_s
end

#default?Boolean

Returns:

  • (Boolean)


101
102
103
104
# File 'lib/tml/language.rb', line 101

def default?
  return true unless application
  application.default_locale == locale
end

#dirObject



106
107
108
# File 'lib/tml/language.rb', line 106

def dir
  right_to_left? ? 'rtl' : 'ltr'
end

#fetchObject

Loads language definition from the service



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/tml/language.rb', line 52

def fetch
  update_attributes(application.api_client.get(
    "language/#{locale}/definition", {},
    {
        cache_key: self.class.cache_key(locale)
    }
  ))
rescue Tml::Exception => ex
  Tml.logger.error("Failed to load language: #{ex}")
  self
end

#full_nameObject



115
116
117
118
# File 'lib/tml/language.rb', line 115

def full_name
  return english_name if english_name == native_name
  "#{english_name} - #{native_name}"
end

#has_definition?Boolean

Returns:

  • (Boolean)


97
98
99
# File 'lib/tml/language.rb', line 97

def has_definition?
  contexts.any?
end

#source_pathObject

build source path to the block



225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/tml/language.rb', line 225

def source_path
  sp = []

  Tml.session.block_options_queue.each do |opts|
    next unless hash_value(opts, :source)
    sp << hash_value(opts, :source)
  end

  sp = sp.reverse
  sp.unshift(Tml.session.current_source)

  sp.join(Tml.config.source_separator)
end

#translate(label, description = nil, tokens = {}, options = {}) ⇒ Object Also known as: tr

Translation Methods

Note - when inline translation mode is enable, cache will not be used and translators will always hit the live service to get the most recent translations

Some cache adapters cache by source, others by key. Some are read-only, some are built on the fly.

There are three ways to call the tr method

tr(label, description = “”, tokens = {}, options = {})

or

tr(label, tokens = {}, options = {})

or

tr(:label => label, :description => “”, :tokens => {}, :options => {})



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/tml/language.rb', line 141

def translate(label, description = nil, tokens = {}, options = {})
  params = Tml::Utils.normalize_tr_params(label, description, tokens, options)
  return params[:label] if params[:label].to_s.strip == '' or params[:label].index('tml:label')
  return params[:label] if params[:label].tml_translated?

  translation_key = Tml::TranslationKey.new({
    :application  => application,
    :label        => params[:label],
    :description  => params[:description],
    :locale       => hash_value(params[:options], :locale) || Tml.session.block_option(:locale) || Tml.config.default_locale,
    :level        => hash_value(params[:options], :level) || Tml.session.block_option(:level) || Tml.config.default_level,
    :syntax       => hash_value(params[:options], :syntax),
    :translations => []
  })

  # pp "Translating #{params[:label]} from: #{translation_key.locale.inspect} to #{locale.inspect} with syntax #{translation_key.syntax}"
  # Tml.logger.info("Translating #{params[:label]} from: #{translation_key.locale.inspect} to #{locale.inspect}")

  params[:tokens] ||= {}
  if params[:tokens].is_a?(Hash)
    params[:tokens][:viewing_user] ||= Tml.session.current_user
  end

  if Tml.config.disabled? or application.nil?
    return translation_key.substitute_tokens(params[:label], params[:tokens], self, params[:options]).tml_translated
  end

  # check if key was ignored on the application level
  if application.ignored_key?(translation_key.key)
    return translation_key.substitute_tokens(params[:label], params[:tokens], self, params[:options]).tml_translated
  end

  # if translations have already been cached in the application, use them
  cached_translations = application.cached_translations(locale, translation_key.key)
  if cached_translations
    translation_key.set_translations(locale, cached_translations)
    return translation_key.translate(self, params[:tokens], params[:options]).tml_translated
  end

  # each key translations will be loaded directly from the API, and registered against "manual" source
  if Tml.session.block_option(:by_key)
    application.register_missing_key(:manual, translation_key)
    translation_key.fetch_translations(locale)
    return translation_key.translate(self, params[:tokens], params[:options]).tml_translated
  end

  # fetch translations grouped by source
  source_key = current_source(params[:options])
  current_source_path = source_path

  # Dynamic sources are never registered under the parent source for fast retrieval
  if Tml.session.block_option(:dynamic)
    current_source_path = source_key
  else
    application.verify_source_path(source_key, current_source_path)
  end

  # Tml.logger.debug("#{self.locale} :  #{params[:label]} : #{source_key}")

  source = application.source(source_key, locale)

  # check if a key was ignored on the source level
  if source.ignored_key?(translation_key.key)
    return translation_key.substitute_tokens(params[:label], params[:tokens], self, params[:options]).tml_translated
  end

  cached_translations = source.cached_translations(locale, translation_key.key)

  if cached_translations
    translation_key.set_translations(locale, cached_translations)
  else
    params[:options] ||= {}
    params[:options][:pending] = true
    application.register_missing_key(current_source_path, translation_key)
  end

  translation_key.translate(self, params[:tokens], params[:options]).tml_translated
rescue Exception => ex
  pp ex, ex.backtrace
  return params[:label]
end

#update_attributes(attrs) ⇒ Object

update language attributes



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/tml/language.rb', line 65

def update_attributes(attrs)
  super

  self.attributes[:contexts] = {}
  if hash_value(attrs, :contexts)
    hash_value(attrs, :contexts).each do |key, context|
      self.attributes[:contexts][key] = Tml::LanguageContext.new(context.merge(:keyword => key, :language => self))
    end
  end

  self.attributes[:cases] = {}
  if hash_value(attrs, :cases)
    hash_value(attrs, :cases).each do |key, lcase|
      self.attributes[:cases][key] = Tml::LanguageCase.new(lcase.merge(:keyword => key, :language => self))
    end
  end
end