]> git.openstreetmap.org Git - rails.git/blob - lib/osm_community_index.rb
Fallback to english locale when looking for community index templates
[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 = YAML.safe_load_file("node_modules/osm-community-index/i18n/en.yaml")["en"]
6
7     files = Rails.root.glob("node_modules/osm-community-index/i18n/*.yaml")
8     files.each do |file|
9       locale = File.basename(file, ".yaml")
10       community_locale_yaml = YAML.safe_load_file(file)[locale]
11       # rails wants language-COUNTRY but osm-community-index uses underscores
12       locale_rails = locale.tr("_", "-")
13
14       data = communities.each_with_object({}) do |community, obj|
15         id = community.id
16
17         strings = community_locale_yaml[id] || {}
18         strings["name"] = resolve_name(community, community_locale_yaml, community_en_yaml)
19
20         obj.deep_merge!("osm_community_index" => { "communities" => { id => strings } })
21       end
22
23       I18n.backend.store_translations locale_rails, data
24     end
25   end
26
27   def self.resolve_name(community, community_locale_yaml, community_en_yaml)
28     # If theres an explicitly translated name then use that
29     translated_name = community_locale_yaml.dig(community.id, "name")
30     return translated_name if translated_name
31
32     # If not, then look up the default translated name for this type of community, and interpolate the template
33     template = community_locale_yaml.dig("_defaults", community.type, "name") ||
34                community_en_yaml.dig("_defaults", community.type, "name")
35     community_name = community_locale_yaml.dig("_communities", community.strings["communityID"])
36     # Change the `{community}` placeholder to `%{community}` and use Ruby's Kernel.format to fill it in.
37     translated_name = format(template.gsub("{", "%{"), { :community => community_name }) if template && community_name
38     return translated_name if translated_name
39
40     # Otherwise fall back to the (English-language) resource name
41     return community.strings["name"] if community.strings["name"]
42
43     # Finally use the (English-language) community name
44     community.strings["community"]
45   end
46 end