]> git.openstreetmap.org Git - rails.git/blob - lib/tag2link.rb
Move tag2link transforms into module
[rails.git] / lib / tag2link.rb
1 # frozen_string_literal: true
2
3 module Tag2link
4   def self.load(path)
5     @dict = build_dict(JSON.parse(path.read)).freeze
6   end
7
8   def self.link(key, value)
9     # skip if it's a full URL
10     return nil if %r{\Ahttps?://}.match?(value)
11
12     url_template = @dict[key]
13     return nil unless url_template
14
15     url_template.gsub("$1", value)
16   end
17
18   def self.build_dict(data)
19     data
20       # exclude deprecated and third-party URLs
21       .reject { |item| item["rank"] == "deprecated" || item["source"] == "wikidata:P3303" }
22       .group_by { |item| item["key"] }
23       .transform_keys { |key| key.sub(/^Key:/, "") }
24       # move preferred to the start of the array
25       .transform_values { |items| items.sort_by { |item| item["rank"] == "preferred" ? 0 : 1 }.uniq { |item| item["url"] } }
26       # exclude any that are ambiguous, i.e. the best and second-best have the same rank
27       .reject { |_key, value| value[1] && value[0]["rank"] == value[1]["rank"] }
28       # keep only the best match
29       .transform_values { |items| items[0]["url"] }
30   end
31 end