DEV: Add validator for search_ranking_weights site setting ()

Follow-up to 6934edd97cfdc855d5882e85415b33f573db120c
This commit is contained in:
Alan Guo Xiang Tan 2023-02-01 06:43:41 +08:00 committed by GitHub
parent 85971a8b67
commit f1ea2a2509
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 46 additions and 0 deletions

@ -2459,6 +2459,7 @@ en:
delete_rejected_email_after_days: "This setting cannot be set lower than the delete_email_logs_after_days setting or greater than %{max}"
invalid_uncategorized_category_setting: "The Uncategorized category cannot be selected if allow uncategorized topics is not allowed"
enable_new_notifications_menu_not_legacy_navigation_menu: "You must set `navigation_menu` to `legacy` before enabling this setting."
invalid_search_ranking_weights: "Value is invalid for search_ranking_weights site setting. Example: '{0.1,0.2,0.3,1.0}'. Note that maximum value for each weight is 1.0."
placeholder:
discourse_connect_provider_secrets:

@ -2213,6 +2213,7 @@ search:
search_ranking_weights:
default: ""
hidden: true
validator: "SearchRankingWeightsValidator"
min_search_term_length:
client: true
default: 3

@ -0,0 +1,19 @@
# frozen_string_literal: true
class SearchRankingWeightsValidator
def initialize(opts = {})
@opts = opts
end
WEIGHT_REGEXP = "1\.0|0\.[0-9]+"
WEIGHTS_REGEXP = /{(?<d_weight>#{WEIGHT_REGEXP}),(?<c_weight>#{WEIGHT_REGEXP}),(?<b_weight>#{WEIGHT_REGEXP}),(?<a_weight>#{WEIGHT_REGEXP})}/
def valid_value?(value)
return true if value.blank?
value.match(WEIGHTS_REGEXP)
end
def error_message
I18n.t("site_settings.errors.invalid_search_ranking_weights")
end
end

@ -0,0 +1,25 @@
# frozen_string_literal: true
RSpec.describe SearchRankingWeightsValidator do
it 'allows a blank value to be set' do
expect do
SiteSetting.search_ranking_weights = ''
end.not_to raise_error
end
it 'raises the right error when value is invalid' do
expect do
SiteSetting.search_ranking_weights = 'test'
end.to raise_error(Discourse::InvalidParameters, /#{I18n.t("site_settings.errors.invalid_search_ranking_weights")}/)
expect do
SiteSetting.search_ranking_weights = '{1.1,0.1,0.2,0.3}'
end.to raise_error(Discourse::InvalidParameters, /#{I18n.t("site_settings.errors.invalid_search_ranking_weights")}/)
end
it 'sets the site setting when value is valid' do
expect do
SiteSetting.search_ranking_weights = '{0.001,0.2,0.003,1.0}'
end.to_not raise_error
end
end