]> git.openstreetmap.org Git - rails.git/blob - lib/osm_community_index.rb
Removed various unused translation keys
[rails.git] / lib / osm_community_index.rb
1 module OsmCommunityIndex
2   def self.add_to_i18n
3     # Filter the communities here to avoid loading excessive numbers of translations
4     communities = Community.where(:type => "osm-lc").where.not(:id => "OSMF")
5     community_en_yaml = if File.exist?("node_modules/osm-community-index/i18n/en.yaml")
6                           YAML.safe_load_file("node_modules/osm-community-index/i18n/en.yaml")["en"]
7                         else
8                           {}
9                         end
10
11     files = Rails.root.glob("node_modules/osm-community-index/i18n/*.yaml")
12     files.each do |file|
13       locale = File.basename(file, ".yaml")
14       community_locale_yaml = YAML.safe_load_file(file)[locale]
15       # rails wants language-COUNTRY but osm-community-index uses underscores
16       locale_rails = locale.tr("_", "-")
17
18       data = communities.each_with_object({}) do |community, obj|
19         id = community.id
20
21         strings = community_locale_yaml[id] || {}
22         strings["name"] = resolve_name(community, community_locale_yaml, community_en_yaml)
23
24         obj.deep_merge!("osm_community_index" => { "communities" => { id => strings } })
25       end
26
27       I18n.backend.store_translations locale_rails, data
28     end
29   end
30
31   def self.resolve_name(community, community_locale_yaml, community_en_yaml)
32     # If theres an explicitly translated name then use that
33     translated_name = community_locale_yaml.dig(community.id, "name")
34     return translated_name if translated_name
35
36     # If not, then look up the default translated name for this type of community, and interpolate the template
37     template = community_locale_yaml.dig("_defaults", community.type, "name") ||
38                community_en_yaml.dig("_defaults", community.type, "name")
39     community_name = community_locale_yaml.dig("_communities", community.strings["communityID"])
40     # Change the `{community}` placeholder to `%{community}` and use Ruby's Kernel.format to fill it in.
41     begin
42       translated_name = format(template.gsub("{", "%{"), { :community => community_name }) if template && community_name
43     rescue KeyError => e
44       Rails.logger.warn e.full_message
45     end
46     return translated_name if translated_name
47
48     # Otherwise fall back to the (English-language) resource name
49     return community.strings["name"] if community.strings["name"]
50
51     # Finally use the (English-language) community name
52     community.strings["community"]
53   end
54 end