Module: Spree::TranslatableResource

Extended by:
ActiveSupport::Concern
Included in:
Category, Collection, LabelTranslatable, Policy, Product, ProductType, Seller, Store
Defined in:
app/models/concerns/spree/translatable_resource.rb

Instance Method Summary collapse

Instance Method Details

#get_field_with_locale(locale, field_name, fallback: false) ⇒ Object



127
128
129
130
# File 'app/models/concerns/spree/translatable_resource.rb', line 127

def get_field_with_locale(locale, field_name, fallback: false)
  # method will return nil if no translation is present due to fallback: false setting
  public_send(field_name, locale: locale, fallback: fallback)
end

#translatable_store ⇒ Object

The store whose supported locales gate which translations are allowed and which locales the matrix exposes. The record's own store when it has one, else the current store.



171
172
173
174
175
176
177
178
179
180
# File 'app/models/concerns/spree/translatable_resource.rb', line 171

def translatable_store
  return self if is_a?(Spree::Store)

  current_store = Spree::Current.store
  # The request's store instance already carries its markets, so a batch
  # of records does not re-read them once per record's own store copy.
  return current_store if current_store && try(:store_id) == current_store.id

  try(:store) || current_store
end

#upsert_translations(values) ⇒ self

Upserts per-locale, per-field translations.

Semantics (omit-to-leave-alone, never implicit-delete):

  • a locale absent from values is untouched
  • a field absent within a present locale is untouched
  • a field set to "" writes an empty string (read falls back to source via Mobility column_fallback); nil deletes that cell

Value normalization (HTML sanitization, slug parameterization) is owned by the model's own writers — this only routes each value to its setter under the right locale.

Parameters:

  • values (Hash{String=>Hash{String=>String,nil}}) —

    locale => { field => value }

Returns:

  • (self)

Raises:

  • (ActiveRecord::RecordInvalid) —

    on an unsupported locale or invalid save



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'app/models/concerns/spree/translatable_resource.rb', line 147

def upsert_translations(values)
  return self if values.blank?

  validate_translation_locales!(values.keys)
  # Accept (and write) the PUBLIC field names so read/write are symmetric
  # with the serializer. `label=` etc. delegate to the internal Mobility
  # field under the active locale.
  allowed = self.class.public_translatable_fields.map(&:to_s)

  transaction do
    values.each do |locale, fields|
      Mobility.with_locale(locale) do
        fields.to_h.slice(*allowed).each { |field, value| public_send("#{field}=", value) }
      end
    end
    save!
  end

  self
end