1 # frozen_string_literal: true
 
   5     @dict = build_dict(JSON.parse(path.read)).freeze
 
   8   def self.link(key, value)
 
   9     # skip if it's a full URL
 
  10     return nil if %r{\Ahttps?://}.match?(value)
 
  12     url_template = @dict[key]
 
  13     return nil unless url_template
 
  15     url_template.gsub("$1", value)
 
  18   def self.build_dict(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"] }