DEV: Introduce `Theme#get_setting` (#24032)

Why this change?

Currently, we do not have a method to easily retrieve a theme setting's
value on the server side. Such a method can be useful in the test
environment where we need to retrieve the theme's setting and use its
value in assertions.

What does this change do?

This change introduces the `Theme#get_setting` instance method.
This commit is contained in:
Alan Guo Xiang Tan 2023-10-23 07:41:40 +08:00 committed by GitHub
parent c06b308895
commit f2a90afa4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 51 additions and 0 deletions

View File

@ -699,6 +699,26 @@ class Theme < ActiveRecord::Base
hash
end
# Retrieves a theme setting
#
# @param setting_name [String, Symbol] The name of the setting to retrieve.
#
# @return [Object] The value of the setting that matches the provided name.
#
# @raise [Discourse::NotFound] If no setting is found with the provided name.
#
# @example
# theme.get_setting("some_boolean") => True
# theme.get_setting("some_string") => "hello"
# theme.get_setting(:some_boolean) => True
# theme.get_setting(:some_string) => "hello"
#
def get_setting(setting_name)
target_setting = settings.find { |setting| setting.name == setting_name.to_sym }
raise Discourse::NotFound unless target_setting
target_setting.value
end
def update_setting(setting_name, new_value)
target_setting = settings.find { |setting| setting.name == setting_name }
raise Discourse::NotFound unless target_setting

View File

@ -1040,6 +1040,37 @@ HTML
end
end
describe "get_setting" do
before do
theme.set_field(target: :settings, name: "yaml", value: <<~YAML)
enabled:
type: bool
default: false
some_value:
type: string
default: "hello"
YAML
ThemeSetting.create!(
theme: theme,
data_type: ThemeSetting.types[:bool],
name: "super_feature_enabled",
)
theme.save!
end
it "returns the value of the setting when given a string represeting the setting name" do
expect(theme.get_setting("enabled")).to eq(false)
expect(theme.get_setting("some_value")).to eq("hello")
end
it "returns the value of the setting when given a symbol represeting the setting name" do
expect(theme.get_setting(:enabled)).to eq(false)
expect(theme.get_setting(:some_value)).to eq("hello")
end
end
describe "#update_setting" do
it "requests clients to refresh if `refresh: true`" do
theme.set_field(target: :settings, name: "yaml", value: <<~YAML)