FEATURE: Allow plugins to register a new locale

This commit is contained in:
Gerhard Schlager
2018-01-25 12:09:18 +01:00
parent ba6cd83e3a
commit eb52c5469e
29 changed files with 480 additions and 71 deletions

View File

@ -29,6 +29,7 @@ class Plugin::Instance
:color_schemes,
:initializers,
:javascripts,
:locales,
:service_workers,
:styles,
:themes].each do |att|
@ -319,6 +320,14 @@ class Plugin::Instance
javascripts << js
end
# @option opts [String] :name
# @option opts [String] :nativeName
# @option opts [String] :fallbackLocale
# @option opts [Hash] :plural
def register_locale(locale, opts = {})
locales << [locale, opts]
end
def register_custom_html(hash)
DiscoursePluginRegistry.custom_html ||= {}
DiscoursePluginRegistry.custom_html.merge!(hash)
@ -427,7 +436,7 @@ JS
end
register_assets! unless assets.blank?
register_locales!
register_service_workers!
seed_data.each do |key, value|
@ -532,6 +541,33 @@ JS
end
end
def register_locales!
root_path = File.dirname(@path)
locales.each do |locale, opts|
opts = opts.dup
opts[:client_locale_file] = File.join(root_path, "config/locales/client.#{locale}.yml")
opts[:server_locale_file] = File.join(root_path, "config/locales/server.#{locale}.yml")
opts[:js_locale_file] = File.join(root_path, "assets/locales/#{locale}.js.erb")
locale_chain = opts[:fallbackLocale] ? [locale, opts[:fallbackLocale]] : [locale]
lib_locale_path = File.join(root_path, "lib/javascripts/locale")
path = File.join(lib_locale_path, "message_format")
opts[:message_format] = find_locale_file(locale_chain, path)
opts[:message_format] = JsLocaleHelper.find_message_format_locale(locale_chain, false) unless opts[:message_format]
path = File.join(lib_locale_path, "moment_js")
opts[:moment_js] = find_locale_file(locale_chain, path)
opts[:moment_js] = JsLocaleHelper.find_moment_locale(locale_chain) unless opts[:moment_js]
if valid_locale?(opts)
DiscoursePluginRegistry.register_locale(locale, opts)
Rails.configuration.assets.precompile << "locales/#{locale}.js"
end
end
end
private
def write_asset(path, contents)
@ -553,4 +589,18 @@ JS
yield plugin
end
def valid_locale?(custom_locale)
File.exist?(custom_locale[:client_locale_file]) &&
File.exist?(custom_locale[:server_locale_file]) &&
File.exist?(custom_locale[:js_locale_file]) &&
custom_locale[:message_format] && custom_locale[:moment_js]
end
def find_locale_file(locale_chain, path)
locale_chain.each do |locale|
filename = File.join(path, "#{locale}.js")
return [locale, filename] if File.exist?(filename)
end
nil
end
end