1 # A map of each OSM key to its formatter URL. For example:
2 # { "ref:vatin" => "https://example.com/$1" }
3 # The JSON data is an array with duplicate entries, which is not efficient for lookups.
4 # So, convert it to a hash and only keep the item with the best rank.
5 TAG2LINK = JSON.parse(Rails.root.join("node_modules/tag2link/index.json").read)
6 # exclude deprecated and third-party URLs
7 .reject { |item| item["rank"] == "deprecated" || item["source"] == "wikidata:P3303" }
8 .group_by { |item| item["key"] }
9 .transform_keys { |key| key.sub(/^Key:/, "") }
10 # move preferred to the start of the array
11 .transform_values { |items| items.sort_by { |item| item["rank"] == "preferred" ? 0 : 1 }.uniq { |item| item["url"] } }
12 # exclude any that are ambiguous, i.e. the best and second-best have the same rank
13 .reject { |_key, value| value[1] && value[0]["rank"] == value[1]["rank"] }
14 # keep only the best match
15 .transform_values { |items| items[0]["url"] }