|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "json" |
| 4 | + |
| 5 | +class TaxonomiesFiltersRemover |
| 6 | + # Parses the plan JSON and removes, from every |
| 7 | + # imported_taxonomies -> <taxonomy_key> -> <label_key> -> filters |
| 8 | + # array, any filter element whose "items" array is blank (nil or empty). |
| 9 | + # |
| 10 | + # @param input_path [String] path to the source JSON file |
| 11 | + # @param output_path [String] path where the cleaned JSON will be written |
| 12 | + # @return [Hash] the cleaned data structure |
| 13 | + def self.call(input_path, output_path = nil) |
| 14 | + output_path ||= input_path |
| 15 | + data = JSON.parse(File.read(input_path)) |
| 16 | + |
| 17 | + imported = data["imported_taxonomies"] |
| 18 | + |
| 19 | + if imported.is_a?(Hash) |
| 20 | + imported.each do |_taxonomy_key, taxonomy_value| |
| 21 | + # Each taxonomy value is a Hash whose keys are labels (e.g. "~ Categories") |
| 22 | + next unless taxonomy_value.is_a?(Hash) |
| 23 | + |
| 24 | + taxonomy_value.each do |_label_key, label_value| |
| 25 | + next unless label_value.is_a?(Hash) |
| 26 | + |
| 27 | + filters = label_value["filters"] |
| 28 | + next unless filters.is_a?(Array) |
| 29 | + |
| 30 | + # Keep only filters where "items" is present AND non-empty |
| 31 | + label_value["filters"] = clean(filters) |
| 32 | + end |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + File.write(output_path, JSON.pretty_generate(data)) |
| 37 | + end |
| 38 | + |
| 39 | + def self.clean(filters) |
| 40 | + filters.reject do |filter| |
| 41 | + items = filter["items"] |
| 42 | + items.nil? || (items.respond_to?(:empty?) && items.empty?) |
| 43 | + end |
| 44 | + end |
| 45 | +end |
0 commit comments