diff --git a/app/services/discourse_translator/base.rb b/app/services/discourse_translator/base.rb index 80d96a66..cf8caa3a 100644 --- a/app/services/discourse_translator/base.rb +++ b/app/services/discourse_translator/base.rb @@ -60,5 +60,12 @@ def self.get_text(topic_or_post) topic_or_post.title end end + + def self.language_supported?(detected_lang) + raise NotImplementedError unless self.const_defined?(:SUPPORTED_LANG_MAPPING) + supported_lang = const_get(:SUPPORTED_LANG_MAPPING) + return false if supported_lang[I18n.locale].nil? + detected_lang != supported_lang[I18n.locale] + end end end diff --git a/plugin.rb b/plugin.rb index f4fa0aca..b25de7fb 100644 --- a/plugin.rb +++ b/plugin.rb @@ -50,10 +50,10 @@ module ::DiscourseTranslator Discourse.redis.sadd?(DiscourseTranslator::LANG_DETECT_NEEDED, object.id) false else - detected_lang != - "DiscourseTranslator::#{SiteSetting.translator}::SUPPORTED_LANG_MAPPING".constantize[ - I18n.locale - ] + detected_lang.to_sym != I18n.locale && + "DiscourseTranslator::#{SiteSetting.translator}".constantize.language_supported?( + detected_lang, + ) end end end diff --git a/spec/serializers/post_serializer_spec.rb b/spec/serializers/post_serializer_spec.rb index 928c3ae5..4303a6be 100644 --- a/spec/serializers/post_serializer_spec.rb +++ b/spec/serializers/post_serializer_spec.rb @@ -89,7 +89,8 @@ describe "when post has DETECTED_LANG_CUSTOM_FIELD matches user locale" do before do - post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] = "en" + I18n.stubs(:locale).returns(:xx) + post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] = "xx" post.save end diff --git a/spec/services/base_spec.rb b/spec/services/base_spec.rb new file mode 100644 index 00000000..5c189374 --- /dev/null +++ b/spec/services/base_spec.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "rails_helper" + +describe DiscourseTranslator::Base do + class TestTranslator < DiscourseTranslator::Base + SUPPORTED_LANG_MAPPING = { en: "en", ar: "ar", es_MX: "es-MX", pt: "pt" } + end + + class EmptyTranslator < DiscourseTranslator::Base + end + + describe ".language_supported?" do + it "raises an error when the method is not implemented" do + expect { EmptyTranslator.language_supported?("en") }.to raise_error(NotImplementedError) + end + + it "returns false when the locale is not supported" do + I18n.stubs(:locale).returns(:xx) + expect(TestTranslator.language_supported?("en")).to eq(false) + end + + it "returns true when the detected language is not the current locale" do + I18n.locale = :pt + expect(TestTranslator.language_supported?("en")).to eq(true) + expect(TestTranslator.language_supported?("ar")).to eq(true) + expect(TestTranslator.language_supported?("es-MX")).to eq(true) + end + + it "returns false when the detected language is the detected locale" do + I18n.locale = :pt + expect(TestTranslator.language_supported?("pt")).to eq(false) + end + end +end