Class: Air18n::PhraseTranslation

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/air18n/phrase_translation.rb

Constant Summary collapse

SPACELESS_LANGUAGES =
[:ja, :zh, :th]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.activity_for_user_id(uid, opts) ⇒ Object



600
601
602
# File 'lib/air18n/phrase_translation.rb', line 600

def self.activity_for_user_id uid, opts
  translator_activity_data uid, opts
end

.aggregate_v3_translation_activity(translation_pairs, opts = {}) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/air18n/phrase_translation.rb', line 355

def self.aggregate_v3_translation_activity(translation_pairs, opts={})
  per_user_locale_month_year =
    Hash.new {|h, year| h[year] =
      Hash.new {|h, month| h[month] =
        Hash.new{|h, user_id| h[user_id] =
          Hash.new{|h, locale| h[locale] =
            Hash.new {|h, day| h[day] = {
              :phrases_translated => 0,
              :phrases_verified => 0,
              :words_translated => 0,
              :words_verified => 0,
              :keys_translated => [],
              :keys_verified => [],
  } } } } } }

  translation_pairs.each do |pair|
    sums = per_user_locale_month_year[
      pair[:datetime].year][
      pair[:datetime].month][
      pair[:user_id]][
      pair[:locale]][
      pair[:datetime].day]
    sums[:words_translated] += pair[:words_translated]
    sums[:words_verified] += pair[:words_verified]
    if pair[:words_verified] > 0
      sums[:keys_verified] << pair[:phrase_key]
      sums[:phrases_verified] += 1
    else
      sums[:keys_translated] << pair[:phrase_key]
      sums[:phrases_translated] += 1
    end
  end

  ret = []

  per_user_locale_month_year.each do |year, months|
    months.each do |month, user_ids|
      user_ids.each do |user_id, locales|
        locales.each do |locale, days|
          if opts[:daily]
            days.each do |day, sums|
              ret << {
                :year => year,
                :month => month,
                :day => day,
                :locale => locale,
                :user_id => user_id,
                :activity => {
                  :num_translations => sums[:phrases_translated],
                  :num_verifications => sums[:phrases_verified],
                  :word_count_translations => sums[:words_translated],
                  :word_count_verifications => sums[:words_verified],
                  :translated_keys => sums[:keys_translated],
                  :verified_keys => sums[:keys_verified],
                }
              }
            end
          else
            monthly_sums = {
              :phrases_translated => 0,
              :phrases_verified => 0,
              :words_translated => 0,
              :words_verified => 0,
              :keys_translated => [],
              :keys_verified => [],
            }
            days.each do |day, sums|
              sums.keys.each do |key|
                monthly_sums[key] += sums[key]
              end
            end
            ret << {
              :year => year,
              :month => month,
              :locale => locale,
              :user_id => user_id,
              :activity => {
                :num_translations => monthly_sums[:phrases_translated],
                :num_verifications => monthly_sums[:phrases_verified],
                :word_count_translations => monthly_sums[:words_translated],
                :word_count_verifications => monthly_sums[:words_verified],
                :translated_keys => monthly_sums[:keys_translated],
                :verified_keys => monthly_sums[:keys_verified],
              }
            }
          end
        end
      end
    end
  end

  ret
end

.compute_v3_translation_activity(user_id, from_date, to_date) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/air18n/phrase_translation.rb', line 490

def self.compute_v3_translation_activity(user_id, from_date, to_date)
  ret = []
  Phrase.select(:id).find_in_batches do |batch|
    pt_scope = PhraseTranslation.where(:phrase_id => batch)
    if from_date
      pt_scope = pt_scope.where("created_at >= ?", from_date)
    end
    if to_date
      pt_scope = pt_scope.where("created_at < ?", to_date)
    end
    if user_id != 0
      pt_scope = pt_scope.where(:user_id => user_id)
    end
    phrase_to_phrase_translations = pt_scope.all.group_by { |pt| [pt.locale, pt.phrase_id] }
    phrase_to_phrase_translations.each do |(locale, phrase_id), phrase_translations|
      phrase_translations.sort_by! { |pt| pt.created_at }

      previous_translation = :uncomputed

      phrase_translations.each do |pt|
        translation_pair = {
          :translation => pt.value,
          :locale => pt.locale,
          :user_id => pt.user_id,
          :datetime => pt.created_at,
          :source_word_count => pt.source_word_count,
          :phrase_key => pt.key,
        }

        if pt.payment_details.present?
          payment_details = JSON.parse(pt.payment_details)
        else
          payment_details = {}
        end

        if !payment_details.include?('v3')
          # If we haven't computed v3 payment details already, compute them
          # and then save details to the PhraseTranslation itself.

          if previous_translation == :uncomputed
            previous_translation = PhraseTranslation.
              where("created_at < ?", phrase_translations.first.created_at - 1.second).
              where(:locale => locale).
              where(:phrase_id => phrase_id).
              order("created_at DESC").
              first
          end

          if previous_translation
            previous_translation_text = previous_translation.value
            previous_translation_user_id = previous_translation.user_id
            was_stale = previous_translation.source_hash != pt.source_hash
          else
            previous_translation_text = ''
            previous_translation_user_id = 0
            was_stale = false
          end

          words_translated, words_verified = self.word_counts_from_translation_pair(
            translation_pair.merge(
              :previous_translation => previous_translation_text,
              :was_stale => was_stale,
              :previous_user_id => previous_translation_user_id,
          ))

          payment_details['v3'] = {
            't' => words_translated,
            'v' => words_verified
          }

          pt.payment_details = payment_details.to_json
          pt.save
        end

        translation_pair[:words_translated] = payment_details['v3']['t']
        translation_pair[:words_verified] = payment_details['v3']['v']

        ret << translation_pair

        previous_translation = pt
      end
    end
  end
  ret
end

.construct_activity(phrase_ids_values_by_type) ⇒ Object

Helper method for translator_activity_data which counts words and payment of a set of translations and verifications, in (is verification bool) => (phrase id => English phrase value map).

Only used by old payment computing method.



609
610
611
612
613
614
# File 'lib/air18n/phrase_translation.rb', line 609

def self.construct_activity(phrase_ids_values_by_type)
  {}.tap do |activity|
    activity[:num_translations], activity[:word_count_translations] = translation_word_count(phrase_ids_values_by_type[false])
    activity[:num_verifications], activity[:word_count_verifications] = translation_word_count(phrase_ids_values_by_type[true])
  end
end

.construct_activity_new(phrase_ids_word_counts_by_type) ⇒ Object

Helper method for translator_activity_data which counts words and payment of a set of translations and verifications, in ((is verification bool => (phrase id => source word count map)).



579
580
581
582
583
584
585
586
587
588
589
# File 'lib/air18n/phrase_translation.rb', line 579

def self.construct_activity_new(phrase_ids_word_counts_by_type)
  {}.tap do |activity|
    activity[:num_translations] = phrase_ids_word_counts_by_type[false].size
    activity[:word_count_translations] = phrase_ids_word_counts_by_type[false].values.sum
    activity[:translated_keys] = phrase_ids_word_counts_by_type[false].keys

    activity[:num_verifications] = phrase_ids_word_counts_by_type[true].size
    activity[:word_count_verifications] = phrase_ids_word_counts_by_type[true].values.sum
    activity[:verified_keys] = phrase_ids_word_counts_by_type[true].keys
  end
end

.create_translation(phrase_id, phrase_key, target_locale, value, user_id, do_xss_check, allow_verification) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/air18n/phrase_translation.rb', line 61

def self.create_translation(phrase_id, phrase_key, target_locale, value, user_id, do_xss_check, allow_verification)
  pt = PhraseTranslation.new
  pt.user_id = user_id
  pt.phrase_id = phrase_id
  pt.key = phrase_key
  pt.locale = target_locale

  latest = pt.phrase.latest_translation(pt.locale)

  pt.value = normalize_translation_value(value)
  normalized_latest_value = latest.present? && normalize_translation_value(latest.value)

  value_same_as_latest = pt.value == normalized_latest_value

  if latest && value_same_as_latest && latest.is_stale && user_id == latest.user_id
    latest.is_stale = false
    if latest.save
      response_obj = {
        :status => 'success',
        :message => 'Translation marked as up-to-date.',
        :phrase_id => latest.phrase_id,
        :key => latest.key,
        :locale => latest.locale,
        :value => latest.value,
        :is_verification => latest.is_verification
      }
    else
      response_obj = { :status => 'error', :message => latest.errors.values.join('; ') }
    end
  else
    do_save = false
    message = ""

    safeness = XssDetector.safe?(pt.phrase.value, pt.value, I18n.default_locale, pt.locale)

    if pt.value.empty?
      message = "Translation empty; nothing saved."
    elsif do_xss_check && !safeness[:safe]
      message = safeness[:reason]
    elsif (latest && value_same_as_latest) && (latest.user_id != 0)
      if !allow_verification
        allowed, error = false, "Verification of non-stale phrases is currently disabled in '#{pt.locale}'"
      else
        allowed, error = pt.verification_allowed?(latest)
      end
      if allowed
        pt.is_verification = true
        do_save = true
        message = "Translation verified."
      else
        message = error
      end
    elsif latest && (latest.user_id != user_id || latest.is_verification)
      # If the translator is different than the last, or the last
      # translation was already a verification, this one is too.
      pt.is_verification = true

      do_save = true
      message = "Translation saved, marked as verified."
    else
      do_save = true
      message = "Translation saved."
    end

    if do_save
      if pt.save
        response_obj = {
          :status => 'success',
          :message => message,
          :phrase_id => pt.phrase_id,
          :key => pt.key,
          :locale => pt.locale,
          :value => pt.value,
          :is_verification => pt.is_verification
        }
      else
        response_obj = {:status => 'error', :message => pt.errors.values.join('; ')}
      end
    else
      response_obj = {:status => 'error', :message => message}
    end
  end

  response_obj
end

.detect_variables(search_in) ⇒ Object



708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/air18n/phrase_translation.rb', line 708

def self.detect_variables(search_in)
  case search_in
  when String
    search_in.scan(/\{\{([\w .\-_]+)\}\}/).flatten +
      search_in.scan(/\%\{(\w+)\}/).flatten +
      search_in.scan(/\%(?:\d\$)?(?:[0\.]\d)?[dfsu@]/).flatten +
      search_in.scan(/__[A-Z_]+__/).flatten

  when Array
    search_in.inject(Set[]) { |carry, item| carry + detect_variables(item) }

  when Hash
    search_in.values.inject(Set[]) { |carry, item| carry + detect_variables(item) }
  else []
  end
end

.keep_key?(key, filter_opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/air18n/phrase_translation.rb', line 643

def self.keep_key?(key, filter_opts={})
  if filter_opts[:exclude_ugc] && I18n.phrase_key_is_ugc?(key)
    return false
  end
  if filter_opts[:exclude_unused] && !I18n.still_used?(key)
    return false
  end
  if filter_opts[:exclude_all]
    return false
  end

  true
end

.list_of_latest_translations(locale) ⇒ Object

For every translated key in a locale, returns list of ids of PhraseTranslations that are the most recent translation of a key.



727
728
729
730
# File 'lib/air18n/phrase_translation.rb', line 727

def self.list_of_latest_translations(locale)
  latest_translations = PhraseTranslation.select("max(id) as max_id").where("locale='#{locale}'").group(:phrase_id).collect{|e| e.max_id}
  latest_translations.empty? ? [0] : latest_translations
end

.reset_latest_and_stale_flags_from_timestamps(locales) ⇒ Object

For every PhraseTranslation in the specific list of locales, resets is_latest and is_stale columns based on phrases.updated_at and phrase_translations.created_at dates.



747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
# File 'lib/air18n/phrase_translation.rb', line 747

def self.reset_latest_and_stale_flags_from_timestamps(locales)
  phrase_id_to_updated_at = {}
  Phrase.find_each do |phrase|
    phrase_id_to_updated_at[phrase.id] = phrase.updated_at
  end

  locales.each do |locale|
    # Output progress to console in case of running this on console.
    latest_translations = PhraseTranslation.select("max(id) as max_id").where("locale='#{locale}'").group(:phrase_id).collect{|e| e.max_id}.to_set

    PhraseTranslation.where(:locale => locale).find_each do |translation|
      phrase_updated_at = phrase_id_to_updated_at[translation.phrase_id]
      if !phrase_updated_at
        # This happens for a few phrases, very weirdly. We could destroy them
        # at some point.
        LoggingHelper.error "What the?! Phrase translation #{translation.inspect} has no corresponding phrase."
        next
      end
      if phrase_updated_at > translation.created_at
        translation.is_stale = true
      end
      if latest_translations.include?(translation.id)
        translation.is_latest = true
      end
      translation.save!(:validate => false)
    end
  end
end

.segment(text) ⇒ Object

Break text into words for purposes of word count. First uses to_s to convert text to a string; so for a nil input, returns empty array. Should only be used for English text, because it only looks at words composed of regexp “w”.



596
597
598
# File 'lib/air18n/phrase_translation.rb', line 596

def self.segment(text)
  text.to_s.scan(/\w+/)
end

.translation_word_count(phrase_ids_to_values) ⇒ Object

Helper method for construct_activity which counts words in a set of translations or verifications, in phrase id => English phrase value map.

Only used by old payment computing method.



620
621
622
# File 'lib/air18n/phrase_translation.rb', line 620

def self.translation_word_count(phrase_ids_to_values)
  [phrase_ids_to_values.count, segment(phrase_ids_to_values.values.join(' ')).size]
end

.translations_for_locale(loc, filter_opts = {}) ⇒ Object

Returns all translations for a locale. filter_opts are passed on to self.keep_key? for filtering.



626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# File 'lib/air18n/phrase_translation.rb', line 626

def self.translations_for_locale(loc, filter_opts={})
  data = {}
  case loc
  when :en
    # Uses a raw unbatched SQL query for speed.
    Phrase.connection.select_all("SELECT `key`, `value` FROM phrases").each do |record|
      data[record['key']] = record['value'] if keep_key?(record['key'], filter_opts)
    end
  else
    # Uses a raw unbatched SQL query for speed.
    PhraseTranslation.connection.select_all(PhraseTranslation.select("`key`, `value`").latest.where(:locale => loc).to_sql).each do |record|
      data[record['key']] = record['value'] if keep_key?(record['key'], filter_opts)
    end
  end
  data
end

.translations_for_locales(locales, filter_opts = {}) ⇒ Object

Provides a complete set of latest translations for specified locales, in nested hash format. filter_opts are passed to keep_key? for optional filtering, like throwing away user-generated content.



50
51
52
53
54
55
56
57
58
59
# File 'lib/air18n/phrase_translation.rb', line 50

def self.translations_for_locales(locales, filter_opts={})

  # set up the hashes we want
  all_locales = {}
  locales.each do |loc|
    data = translations_for_locale(loc, filter_opts)
    all_locales[loc] = data
  end
  all_locales
end

.translator_activity_data(user_id = 0, opts = {}) ⇒ Object



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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/air18n/phrase_translation.rb', line 186

def self.translator_activity_data user_id=0, opts={}
  user_criterion = user_id > 0 ? "AND pt.user_id=#{user_id}" : "AND NOT pt.user_id=0"
  since_criterion = "AND pt.created_at >= '#{opts[:since].to_formatted_s(:db)}'" if opts[:since]
  to_criterion = "AND pt.created_at < '#{opts[:to].to_formatted_s(:db)}'" if opts[:to]
  sql = "SELECT #{created_at_year_sql} year, #{created_at_month_sql} month, pt.user_id user_id, pt.locale locale, #{created_at_day_sql} day, p.id phrase_id, p.value phrase_value, pt.is_verification FROM phrase_translations pt, phrases p WHERE pt.phrase_id=p.id #{user_criterion} #{since_criterion} #{to_criterion} GROUP BY #{created_at_year_sql}, #{created_at_month_sql}, pt.user_id, pt.locale, pt.phrase_id"
  res = self.connection.select_rows(sql)
  phrases_per_user_locale_month_year =
    Hash.new {|h, year| h[year] =
      Hash.new {|h, month| h[month] =
        Hash.new{|h, user_id| h[user_id] =
          Hash.new{|h, locale| h[locale] =
            Hash.new {|h, day| h[day] =
              Hash.new {|h, is_verification| h[is_verification] =
                Hash.new
  } } } } } }

  res.each do |row|
    year, month, user_id, locale, day, phrase_id, phrase_value, is_verification = row
    is_verification = (is_verification == 1 || is_verification == 't')
    phrases_per_user_locale_month_year[year.to_i][month.to_i][user_id][locale][day.to_i][is_verification].merge!({phrase_id => phrase_value})
  end

  activities = []
  phrases_per_user_locale_month_year.each do |year, months|
    months.each do |month, user_ids|
      user_ids.each do |user_id, locales|
        locales.each do |locale, days|
          if opts[:daily]
            days.each do |day, phrase_ids_values_by_type|
              activities << {:year => year, :month => month, :day => day, :locale => locale, :user_id => user_id, :activity => construct_activity(phrase_ids_values_by_type)}
            end
          else
            monthly_phrase_ids_values_by_type = { false => {}, true => {} }
            days.each do |_, phrase_ids_values_by_type|
              [false, true].each do |is_verification|
                monthly_phrase_ids_values_by_type[is_verification].merge!(phrase_ids_values_by_type[is_verification])
              end
            end
            activity = construct_activity(monthly_phrase_ids_values_by_type)
            translation_ids = monthly_phrase_ids_values_by_type[false].keys
            if translation_ids.empty?
              activity[:num_phrases_prev_translated] = 0
            else
              activity[:num_phrases_prev_translated] = self.count_by_sql("select count(distinct(phrase_id)) from phrase_translations where user_id = #{user_id} and phrase_id in (#{translation_ids.join(',')}) and locale = '#{locale}' and created_at < '#{year}-#{month}-01'")
            end
            activities << {:year => year, :month => month, :locale => locale, :user_id => user_id, :activity => activity}
          end
        end
      end
    end
  end
  activities.sort do |a,b|
    if a[:year] == b[:year]
      if a[:month] == b[:month]
        if a[:user_id] == b[:user_id]
          if a[:locale] == b[:locale]
            if !a[:day] || !b[:day] || a[:day] == b[:day]
              0
            else
              a[:day] <=> b[:day]
            end
          else
            a[:locale] <=> b[:locale]
          end
        else
          a[:user_id] <=> b[:user_id]
        end
      else
        a[:month] <=> b[:month]
      end
    else
      a[:year] <=> b[:year]
    end
  end
end

.translator_activity_data_master(user_id = 0, opts = {}) ⇒ Object

Computes monthly activity for months between opts and opts. If opts is not set, starts from the current month. If opts is not set, goes back until a month in which there is no activity. If user_id is 0, computes activity for all users.



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/air18n/phrase_translation.rb', line 161

def self.translator_activity_data_master(user_id = 0, opts = {})
  to_date = opts[:to] ? opts[:to] : Date.today
  d = to_date.beginning_of_month
  activities = []

  while true
    break if opts[:since] && d < opts[:since]

    if d < Date.new(2012, 8, 02)
      activity_for_month = translator_activity_data(user_id, opts.merge(:since => d, :to => (d >> 1)))
    elsif d < Date.new(2012, 10, 02)
      activity_for_month = translator_activity_data_new(user_id, opts.merge(:since => d, :to => (d >> 1)))
    else
      activity_for_month = translator_activity_data_v3(user_id, opts.merge(:since => d, :to => (d >> 1)))
    end

    break if !opts[:since] && activity_for_month.blank?

    activities += activity_for_month
    d = d << 1
  end

  activities
end

.translator_activity_data_new(user_id = 0, opts = {}) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/air18n/phrase_translation.rb', line 262

def self.translator_activity_data_new user_id=0, opts={}
  user_criterion = user_id > 0 ? "AND pt.user_id=#{user_id}" : "AND NOT pt.user_id=0"
  since_criterion = "AND pt.created_at >= '#{opts[:since].to_formatted_s(:db)}'" if opts[:since]
  to_criterion = "AND pt.created_at < '#{opts[:to].to_formatted_s(:db)}'" if opts[:to]
  sql = "SELECT #{created_at_year_sql} year, #{created_at_month_sql} month, pt.user_id user_id, pt.locale locale, #{created_at_day_sql} day, p.id phrase_id, pt.source_word_count source_word_count, pt.key, pt.source_hash source_hash, pt.is_verification FROM phrase_translations pt, phrases p WHERE pt.phrase_id=p.id #{user_criterion} #{since_criterion} #{to_criterion} GROUP BY #{created_at_year_sql}, #{created_at_month_sql}, pt.user_id, pt.locale, pt.phrase_id, pt.source_hash, pt.is_verification"
  res = self.connection.select_rows(sql)
  phrases_per_user_locale_month_year =
    Hash.new {|h, year| h[year] =
      Hash.new {|h, month| h[month] =
        Hash.new{|h, user_id| h[user_id] =
          Hash.new{|h, locale| h[locale] =
            Hash.new {|h, day| h[day] =
              Hash.new {|h, is_verification| h[is_verification] =
                Hash.new
  } } } } } }

  res.each do |row|
    year, month, user_id, locale, day, phrase_id, source_word_count, key, source_hash, is_verification = row
    is_verification = (is_verification == 1 || is_verification == 't')
    phrases_per_user_locale_month_year[year.to_i][month.to_i][user_id][locale][day.to_i][is_verification].merge!({[key, source_hash] => source_word_count})
  end

  activities = []
  phrases_per_user_locale_month_year.each do |year, months|
    months.each do |month, user_ids|
      user_ids.each do |user_id, locales|
        locales.each do |locale, days|

          # Caalesce into monthly stats.
          monthly_phrase_ids_word_counts_by_type = { false => {}, true => {} }
          days.each do |_, phrase_ids_word_counts_by_type|
            monthly_phrase_ids_word_counts_by_type[false].merge!(phrase_ids_word_counts_by_type[false])
          end
          days.each do |_, phrase_ids_word_counts_by_type|
            phrase_ids_word_counts_by_type[true].each do |phrase_id, word_count|
              if !monthly_phrase_ids_word_counts_by_type[false].include?(phrase_id)
                monthly_phrase_ids_word_counts_by_type[true][phrase_id] = word_count
              end
            end
          end

          verification_sum_of_days = 0
          translation_sum_of_days = 0

          if opts[:daily]
            days.each do |day, phrase_ids_word_counts_by_type|
              daily_phrase_ids_word_counts_by_type = { false => phrase_ids_word_counts_by_type[false], true => {} }
              phrase_ids_word_counts_by_type[true].each do |phrase_id, word_count|
                if !monthly_phrase_ids_word_counts_by_type[false].include?(phrase_id)
                  daily_phrase_ids_word_counts_by_type[true][phrase_id] = word_count
                end
              end
              activities << {:year => year, :month => month, :day => day, :locale => locale, :user_id => user_id, :activity => construct_activity_new(daily_phrase_ids_word_counts_by_type)}
              translation_sum_of_days += activities.last[:activity][:word_count_translations]
              verification_sum_of_days += activities.last[:activity][:word_count_verifications]
            end
          else
            activity = construct_activity_new(monthly_phrase_ids_word_counts_by_type)
            activities << {:year => year, :month => month, :locale => locale, :user_id => user_id, :activity => activity}
          end
        end
      end
    end
  end
  activities.sort do |a,b|
    if a[:year] == b[:year]
      if a[:month] == b[:month]
        if a[:user_id] == b[:user_id]
          if a[:locale] == b[:locale]
            if !a[:day] || !b[:day] || a[:day] == b[:day]
              0
            else
              a[:day] <=> b[:day]
            end
          else
            a[:locale] <=> b[:locale]
          end
        else
          a[:user_id] <=> b[:user_id]
        end
      else
        a[:month] <=> b[:month]
      end
    else
      a[:year] <=> b[:year]
    end
  end
end

.translator_activity_data_v3(user_id = 0, opts = {}) ⇒ Object



351
352
353
# File 'lib/air18n/phrase_translation.rb', line 351

def self.translator_activity_data_v3 user_id=0, opts={}
  aggregate_v3_translation_activity(compute_v3_translation_activity(user_id, opts[:since], opts[:to]), opts)
end

.word_counts_from_translation_pair(translation_pair) ⇒ Object



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
# File 'lib/air18n/phrase_translation.rb', line 451

def self.word_counts_from_translation_pair(translation_pair)
  if translation_pair[:previous_translation].blank?
    proportion_translated = 1.0
    proportion_verified = 0.0
  elsif !translation_pair[:was_stale] &&
        translation_pair[:previous_user_id] == translation_pair[:user_id]
    # Don't pay anything for retranslating your own work.
    proportion_translated = 0.0
    proportion_verified = 0.0
  else
    # Pay for translating changed/added parts, and for verifying the rest.

    if SPACELESS_LANGUAGES.include?(translation_pair[:locale].to_sym)
      distance = levenshtein_distance_fast(
        translation_pair[:previous_translation].split(''),
        translation_pair[:translation].split(''),
        1, 0, 1)
      compare_to = translation_pair[:previous_translation].size
    else
      distance = levenshtein_distance_fast(
        translation_pair[:previous_translation].scan(/[[:alnum:]]+/),
        translation_pair[:translation].scan(/[[:alnum:]]+/),
        1, 0, 1)
      compare_to = translation_pair[:previous_translation].scan(/[[:alnum:]]+/).size
    end

    if compare_to == 0
      proportion_translated = 0.0
      proportion_verified = 0.0
    else
      proportion_translated = [distance.to_f / compare_to.to_f, 1.0].min
      proportion_verified = 1.0 - proportion_translated
    end
  end

  [(translation_pair[:source_word_count] * proportion_translated).ceil,
   (translation_pair[:source_word_count] * proportion_verified).floor]
end

Instance Method Details

#check_matching_variablesObject



674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# File 'lib/air18n/phrase_translation.rb', line 674

def check_matching_variables
  our_variables = self.variables
  their_variables = self.phrase.variables

  if SmartCount::applies?(self.phrase.value) || SmartCount::applies?(self.value)
    our_variables = SmartCount::dedupe_things_like_tags_or_variables(
      self.locale, our_variables)
    their_variables = SmartCount::dedupe_things_like_tags_or_variables(
      I18n.default_locale, their_variables)
  end

  our_extra = our_variables - their_variables
  their_extra = their_variables - our_variables
  problems = []
  if !their_extra.empty? || !our_extra.empty?
    if !their_extra.empty?
      problems << "Var #{quote_vars their_extra} missing from translation"
    end
    if !our_extra.empty?
      problems << "Var #{quote_vars our_extra} should not be in translation"
    end
  elsif our_variables.group_by{|t| t} != their_variables.group_by{|t| t}
    # This is to catch smart-count-related cases.
    problems << "Vars don't match: #{quote_vars their_variables} vs. #{quote_vars our_variables}"
  end
  unless problems.empty?
    self.errors.add(:value, problems.join('; '))
  end
end

#check_max_lengthObject



664
665
666
667
668
669
670
671
672
# File 'lib/air18n/phrase_translation.rb', line 664

def check_max_length
  if /maxlength:(\d+)/ =~ key
    max_length = $1.to_i
    length = value.size
    if length > max_length
      self.errors.add(:value, "Translation has #{length} characters, maximum length is #{max_length} characters.")
    end
  end
end

#check_plural_formsObject



657
658
659
660
661
662
# File 'lib/air18n/phrase_translation.rb', line 657

def check_plural_forms
  result = SmartCount::valid?(self.phrase.value, self.value, I18n.default_locale, self.locale)
  if !result[:valid]
    self.errors.add(:value, result[:reason])
  end
end

#latest?Boolean

Returns:

  • (Boolean)


736
737
738
# File 'lib/air18n/phrase_translation.rb', line 736

def latest?
  is_latest
end

#previous_translationObject

Returns the previous translation, or nil if there was none.

May return a phrase translation with a different source_hash.



150
151
152
153
154
155
# File 'lib/air18n/phrase_translation.rb', line 150

def previous_translation
  PhraseTranslation.where(:locale => locale,
                          :phrase_id => phrase_id).
                    where('`phrase_translations`.id < ?', id).
                    last
end

#set_latestObject

Sets is_latest of this translation, and removes the is_latest flag from all previous translations.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/air18n/phrase_translation.rb', line 25

def set_latest
  self.is_latest = true
  other_translations = PhraseTranslation.find_all_by_phrase_id_and_locale(phrase_id, locale)
  other_translations.each do |other|
    if other.id != id && other.is_latest
      other.is_latest = false

      # Skip validations. This is because in the case where a translator is
      # making a new (valid) translation where the previous translation was
      # invalid, we want to be able to still mark the old translation as
      # invalid.
      other.save!(:validate => false)
    end
  end
end

#set_source_hashObject

Sets the source_word_count and source_hash fields.



42
43
44
45
# File 'lib/air18n/phrase_translation.rb', line 42

def set_source_hash
  self.source_word_count = PhraseTranslation.segment(phrase.value).size
  self.source_hash = phrase.compute_value_hash
end

#stale?Boolean

Returns:

  • (Boolean)


740
741
742
# File 'lib/air18n/phrase_translation.rb', line 740

def stale?
  is_stale
end

#variablesObject



704
705
706
# File 'lib/air18n/phrase_translation.rb', line 704

def variables
  PhraseTranslation.detect_variables(value)
end

#verification?Boolean

Returns:

  • (Boolean)


732
733
734
# File 'lib/air18n/phrase_translation.rb', line 732

def verification?
  is_verification
end

#verification_allowed?(latest_translation) ⇒ Boolean

Returns:

  • (Boolean)


776
777
778
779
780
781
782
783
784
# File 'lib/air18n/phrase_translation.rb', line 776

def verification_allowed?(latest_translation)
  if latest_translation.is_verification? && !latest_translation.stale?
    return [false, "Translation already verified; nothing saved."]
  end
  if user_id == latest_translation.user_id && !latest_translation.stale?
    return [false, "You last translated this phrase, so somebody else must verify it."]
  end
  return [true]
end