Sha256: aeaf90c23dd0a9dc3926eaf37104868211668c567342e7f037834bf766af97a2

Contents?: true

Size: 1.83 KB

Versions: 5

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

module Decidim
  module Decidim::DecidimAwesome
    # This type represents a translated field in multiple languages.
    class TranslatedCustomFieldsType < Decidim::Api::Types::BaseObject
      description "A translated field"

      field :locales, [GraphQL::Types::String, { null: true }], description: "Lists all the locales in which this translation is available", null: true

      field :translations, [LocalizedCustomFieldsType, { null: true }], description: "All the localized custom fields for this translation.", null: false do
        argument :locales, [GraphQL::Types::String], description: "A list of locales to scope the translations to.", required: false
      end

      field :translation, GraphQL::Types::JSON, description: "Returns a single translation given a locale.", null: true do
        argument :locale, GraphQL::Types::String, "A locale to search for", required: true
      end

      def locales
        (defined_translations.keys + machine_translations.keys).uniq
      end

      def translation(locale: "")
        display_translations[locale]
      end

      def translations(locales: [])
        translations = display_translations
        translations = translations.slice(*locales) unless locales.empty?

        translations.map { |locale, fields| OpenStruct.new(locale:, fields:, machine_translated: defined_translations[locale].blank?) }
      end

      private

      def display_translations
        @display_translations ||= locales.index_with do |locale|
          defined_translations[locale].presence || machine_translations[locale]
        end
      end

      def defined_translations
        object.stringify_keys.except("machine_translations")
      end

      def machine_translations
        object.stringify_keys["machine_translations"]&.stringify_keys || {}
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
decidim-decidim_awesome-0.12.0 lib/decidim/decidim_awesome/api/types/translated_custom_fields_type.rb
decidim-decidim_awesome-0.11.4 lib/decidim/decidim_awesome/api/types/translated_custom_fields_type.rb
decidim-decidim_awesome-0.11.3 lib/decidim/decidim_awesome/api/types/translated_custom_fields_type.rb
decidim-decidim_awesome-0.11.2 lib/decidim/decidim_awesome/api/types/translated_custom_fields_type.rb
decidim-decidim_awesome-0.11.1 lib/decidim/decidim_awesome/api/types/translated_custom_fields_type.rb