Module: Elasticsearch::Model::MongoidExtensions::Localized::Serializing

Defined in:
lib/elasticsearch/model/mongoid_extensions/localized.rb

Instance Method Summary collapse

Instance Method Details

#as_indexed_json(*args) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/elasticsearch/model/mongoid_extensions/localized.rb', line 29

def as_indexed_json(*args)
  super(*args).tap do |obj|
    fields.select { |_, field| field.localized? }.each do |name, field|
      aliased_name = field.options[:as].to_s
      translations_field_name = [name, 'translations'].join('_')
      field_obj = send(translations_field_name)
      field_key = aliased_name.presence || name

      obj[field_key] = I18n.available_locales.each_with_object({}) do |locale, res|
        res[locale.to_s] = field_obj[locale.to_s].presence || field_obj[locale]

        next if res[locale].present?

        if field.send(:fallbacks?) && ::I18n.respond_to?(:fallbacks)
          next unless fallbacks_for_locale = ::I18n.fallbacks[locale]
          next unless fallback_locale = fallbacks_for_locale.map(&:to_s).find{ |loc| field_obj.has_key?(loc) && field_obj[loc].present? }
          res[locale.to_s] = field_obj[fallback_locale]
        end
      end

      obj
    end
  end
end