Skip to content

Commit

Permalink
Add getter for configured class names
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mamhoff committed Jan 15, 2025
1 parent f4b32ef commit 85c2ac3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
4 changes: 4 additions & 0 deletions core/lib/spree/preferences/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions core/spec/models/spree/preferences/configuration_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

0 comments on commit 85c2ac3

Please sign in to comment.