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