Module: Spree::TranslatableResource

Extended by:
ActiveSupport::Concern
Included in:
Policy, PresentationTranslatable, Product, Store, Taxon, Taxonomy
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



57
58
59
60
# File 'app/models/concerns/spree/translatable_resource.rb', line 57

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_storeObject

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.



101
102
103
104
105
# File 'app/models/concerns/spree/translatable_resource.rb', line 101

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

  try(:store) || Spree::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



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'app/models/concerns/spree/translatable_resource.rb', line 77

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