Module: OpenLoam::Translatable

Extended by:
ActiveSupport::Concern
Defined in:
lib/open_loam/translatable.rb

Overview

Per-record, per-locale translations of DATA fields — a product name, a category label — distinct from Rails i18n (developer UI strings, still Rails-native and out of scope here).

class Equipment < OpenLoam::TenantRecord
include OpenLoam::Translatable
translates :name, :description
end

READ OVERLAY: the field reader returns the translation for the CURRENT locale (OpenLoam.locale) when one exists, else the record's own COLUMN value — the base is the fallback and stays authoritative for the default locale:

equipment.name                  # => overlay for OpenLoam.locale, else base
equipment.name(locale: "de")    # => explicit locale, else base
equipment.set_translation(:name, "de", "Bagger")
equipment.translations_for(:name)  # => { "de" => "Bagger", ... }

Writes still go through the ordinary name= writer to the base column, so translations are purely additive rows in open_loam_translations — the base value is never overwritten or lost.

Instance Method Summary collapse

Instance Method Details

#open_loam_translation_value(field, locale = nil) ⇒ Object

The stored translation for a field in a locale (default: the current one), or nil when there is none.



67
68
69
70
71
72
# File 'lib/open_loam/translatable.rb', line 67

def open_loam_translation_value(field, locale = nil)
  locale = (locale || OpenLoam.locale).to_s
  return nil if locale.blank?

  open_loam_translations.detect { |t| t.field == field.to_s && t.locale == locale }&.value
end

#set_translation(field, locale, value) ⇒ Object

Raises:



74
75
76
77
78
79
80
81
82
# File 'lib/open_loam/translatable.rb', line 74

def set_translation(field, locale, value)
  raise OpenLoam::Error, "#{field} is not translatable on #{self.class.name}" unless self.class.open_loam_translatable?(field)

  row = open_loam_translations.find_or_initialize_by(field: field.to_s, locale: locale.to_s)
  row.value = value
  row.save!
  open_loam_translations.reset
  value
end

#translations_for(field) ⇒ Object



84
85
86
# File 'lib/open_loam/translatable.rb', line 84

def translations_for(field)
  open_loam_translations.select { |t| t.field == field.to_s }.to_h { |t| [ t.locale, t.value ] }
end