From 85c2ac35cfa5eae486a21143221ed590cd165a39 Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Sat, 21 Dec 2024 15:37:42 +0100 Subject: [PATCH] Add getter for configured class names When configuring Flickwerk, we need a way to get at class names without constantizing (i.e. loading) those classes. This adds some specs for the `class_name_attribute` class method on Spree::Preferences::Configuration, and generates a new getter that has `_name` attached to the method to get just the string name. --- core/lib/spree/preferences/configuration.rb | 4 ++++ .../models/spree/preferences/configuration_spec.rb | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/core/lib/spree/preferences/configuration.rb b/core/lib/spree/preferences/configuration.rb index 3f7336e7e94..b8cca7ea0e3 100644 --- a/core/lib/spree/preferences/configuration.rb +++ b/core/lib/spree/preferences/configuration.rb @@ -173,6 +173,10 @@ def self.class_name_attribute(name, default:) class_name = class_name.constantize if class_name.is_a?(String) class_name end + + define_method("#{name}_name") do + instance_variable_get(ivar) || default + end end def self.by_version(*args) diff --git a/core/spec/models/spree/preferences/configuration_spec.rb b/core/spec/models/spree/preferences/configuration_spec.rb index 572ad357778..59df1e12133 100644 --- a/core/spec/models/spree/preferences/configuration_spec.rb +++ b/core/spec/models/spree/preferences/configuration_spec.rb @@ -7,6 +7,7 @@ Class.new(Spree::Preferences::Configuration) do preference :color, :string, default: :blue versioned_preference :foo, :boolean, initial_value: true, boundaries: { "3.0" => false } + class_name_attribute :order_recalculator_class, default: 'Spree::OrderUpdater' end.new end @@ -84,4 +85,16 @@ end end end + + describe ".class_name_attribute" do + it "allows getting the constant of a configurable class" do + config.order_recalculator_class = 'Spree::OrderUpdater' + expect(config.order_recalculator_class).to eq Spree::OrderUpdater + end + + it "allows getting the string name of the class" do + config.order_recalculator_class = 'Spree::OrderUpdater' + expect(config.order_recalculator_class_name).to eq 'Spree::OrderUpdater' + end + end end