Class: Translated::TranslatedTextField

Inherits:
ApplicationRecord
  • Object
show all
Defined in:
app/models/translated/translated_text_field.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.sync_allObject

Re-translate all records. Useful after adding a new locale.



36
37
38
# File 'app/models/translated/translated_text_field.rb', line 36

def self.sync_all
  find_each(&:update_translations)
end

.sync_missingObject

Sync only records that are missing translations.



31
32
33
# File 'app/models/translated/translated_text_field.rb', line 31

def self.sync_missing
  with_missing_translations.find_each(&:update_translations)
end

Instance Method Details

#for_locale(locale) ⇒ Object



40
41
42
# File 'app/models/translated/translated_text_field.rb', line 40

def for_locale(locale)
  content.fetch(locale.to_s) { content[language] }
end

#missing_translations?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'app/models/translated/translated_text_field.rb', line 44

def missing_translations?
  (I18n.available_locales.map(&:to_s) - content.keys).any?
end

#set_locale(locale, value) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'app/models/translated/translated_text_field.rb', line 48

def set_locale(locale, value)
  locale = locale.to_s
  self.language = locale

  self.content ||= {}
  self.content[locale] = value

  @_needs_translations = content_changed?
  value
end

#update_translationsObject



59
60
61
62
63
64
65
66
67
68
69
# File 'app/models/translated/translated_text_field.rb', line 59

def update_translations
  source = content[language]

  I18n.available_locales.each do |locale|
    next if locale == language.to_sym

    content[locale.to_s] = source.presence && Translator.new.translate(source, from: language, to: locale.to_s)
  end

  save!
end