Skip to content

Commit 5b72470

Browse files
Add task to remove blank filters
1 parent ba27e98 commit 5b72470

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

lib/tasks/decidim_taxonomies.rake

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
require "decidim/maintenance"
4+
5+
namespace :decidim do
6+
namespace :taxonomies do
7+
desc "Removes filters from each tmp/taxonomies/*_plan.json (rewrites files in place)"
8+
task :remove_filters_from_all_plans, [] => :environment do |_task, _args|
9+
files = Rails.root.glob("tmp/taxonomies/*_plan.json")
10+
if files.empty?
11+
log.warn "No *_plan.json files found in tmp/taxonomies"
12+
next
13+
end
14+
15+
files.each do |file_path|
16+
log.info "Removing filters from #{file_path}"
17+
TaxonomiesFiltersRemover.call(file_path)
18+
end
19+
log.info "Done."
20+
end
21+
end
22+
end

0 commit comments

Comments
 (0)