<commit_before># frozen_string_literal: true

module GobiertoCommon::CustomFieldValue
  class VocabularyOptions < Base
    def value
      vocabulary.terms.where(id: raw_value)
    end

    def value=(value)
      value = value.id if value.is_a?(GobiertoCommon::Term)

      if custom_field.configuration.vocabulary_type == "tags"
        existing_ids = vocabulary.terms.where(id: value).pluck(:id).map(&:to_s)
        new_tags = value - existing_ids
        start_position = vocabulary.terms.maximum(:position).to_i + 1

        new_terms_ids = new_tags.map.with_index do |new_term, i|
          vocabulary.terms.create(name: new_term, position: start_position + i).id
        end.compact
        value = existing_ids + new_terms_ids
      end

      super
    end

    def vocabulary
      return unless custom_field.options.present?

      GobiertoCommon::Vocabulary.find_by(id: custom_field.options["vocabulary_id"])
    end
  end
end<commit_msg>Avoid exception when no vocabulary terms are assigned to custom field<commit_after># frozen_string_literal: true

module GobiertoCommon::CustomFieldValue
  class VocabularyOptions < Base
    def value
      vocabulary.terms.where(id: raw_value)
    end

    def value=(value)
      value = value.id if value.is_a?(GobiertoCommon::Term)

      if custom_field.configuration.vocabulary_type == "tags"
        if value && value.any?
          existing_ids = vocabulary.terms.where(id: value).pluck(:id).map(&:to_s)
          new_tags = value - existing_ids
          start_position = vocabulary.terms.maximum(:position).to_i + 1

          new_terms_ids = new_tags.map.with_index do |new_term, i|
            vocabulary.terms.create(name: new_term, position: start_position + i).id
          end.compact
          value = existing_ids + new_terms_ids
        else
          value = []
        end
      end

      super
    end

    def vocabulary
      return unless custom_field.options.present?

      GobiertoCommon::Vocabulary.find_by(id: custom_field.options["vocabulary_id"])
    end
  end
end
{'fraction_non_alphanumeric': 0.08842208109428432, 'fraction_numerical': 0.0009770395701025891, 'mean_word_length': 2.900952380952381, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4264540', 'n_tokens_mistral': 651, 'n_tokens_neox': 619, 'n_words': 131}