From f2a90afa4cd0c770aef51b14c6538f9d9a07f452 Mon Sep 17 00:00:00 2001 From: Alan Guo Xiang Tan Date: Mon, 23 Oct 2023 07:41:40 +0800 Subject: [PATCH] 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. --- app/models/theme.rb | 20 ++++++++++++++++++++ spec/models/theme_spec.rb | 31 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/app/models/theme.rb b/app/models/theme.rb index 87b566c3073..bdba5fc67a3 100644 --- a/app/models/theme.rb +++ b/app/models/theme.rb @@ -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 diff --git a/spec/models/theme_spec.rb b/spec/models/theme_spec.rb index 6ffa42b4fcf..27498852276 100644 --- a/spec/models/theme_spec.rb +++ b/spec/models/theme_spec.rb @@ -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)