From 03c02ef78ec0fb4e33466c01c5b37aa4d4710622 Mon Sep 17 00:00:00 2001 From: evazion Date: Sat, 3 Sep 2022 18:45:09 -0500 Subject: [PATCH] autocomplete: fix accidental API breakage. Fix /autocomplete.json returning results like this: [ { "table": { "type": "tag-word", "label": "long hair", "value": "long_hair", "category": 0, "post_count": 2818211, "antecedent": null } }, ] instead of like this: [ { "type": "tag-word", "label": "long hair", "value": "long_hair", "category": 0, "post_count": 2818211, }, ] Also change it so that optional attributes like `antecedent` aren't returned if they're null. This could be a minor breaking change if users rely on these attributes always being present. Lastly change XML results to look like this: tag-word long_hair 0 2801117 instead of like this: tag hair_ornament 0 883340 --- app/logical/autocomplete_service.rb | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/app/logical/autocomplete_service.rb b/app/logical/autocomplete_service.rb index f6a28f3c6..00a7cad0c 100644 --- a/app/logical/autocomplete_service.rb +++ b/app/logical/autocomplete_service.rb @@ -31,6 +31,17 @@ class AutocompleteService attr_reader :query, :type, :limit, :current_user, :enabled alias_method :enabled?, :enabled + # A Result represents a single autocomplete entry. `label` is the pretty name to + # display in the autocomplete menu and `value` is the actual string to insert. + class Result < Struct.new(:type, :label, :value, :category, :post_count, :id, :level, :antecedent, keyword_init: true) + include ActiveModel::Serializers::JSON + include ActiveModel::Serializers::Xml + + def serializable_hash(...) + to_h.compact_blank + end + end + # Perform completion for the given search type and query. # @param query [String] the string being completed # @param type [String] the type of completion being performed @@ -71,7 +82,7 @@ class AutocompleteService autocomplete_saved_search_label(query) else [] - end.map { |result| OpenStruct.new(result) } + end.map { |result| Result.new(result) } end # Complete a tag search (a regular tag or a metatag)