Skip to content

Commit

Permalink
Return fully namespaced ingredient constant
Browse files Browse the repository at this point in the history
Using const_get returns the constant from within the Alchemy::Ingredients
module, not the full constant. This can lead to errors with ingredients
that have a reserved constant name (like the File ingredient)
  • Loading branch information
tvdeyen committed Aug 6, 2021
1 parent c841676 commit 2840cb3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions app/models/alchemy/ingredient.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def related_object_alias(name, class_name:)

# Returns an ingredient class by type
#
# Raises ArgumentError if there is no such class in the
# Raises NameError if there is no such class in the
# +Alchemy::Ingredients+ module namespace.
#
# If you add custom ingredient class,
Expand All @@ -89,7 +89,7 @@ def related_object_alias(name, class_name:)
# @param [String] The ingredient class name to constantize
# @return [Class]
def ingredient_class_by_type(ingredient_type)
Alchemy::Ingredients.const_get(ingredient_type.to_s.classify.demodulize)
normalize_type(ingredient_type).constantize
end

# Modulize ingredient type
Expand Down
28 changes: 28 additions & 0 deletions spec/models/alchemy/ingredient_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,34 @@
end
end

describe ".ingredient_class_by_type" do
subject { described_class.ingredient_class_by_type(ingredient_type) }

context "with a known ingredient class" do
let(:ingredient_type) { "Text" }

it "returns full ingredient constant" do
expect(subject).to eq(Alchemy::Ingredients::Text)
end
end

context "with unkown ingredient class" do
let(:ingredient_type) { "Foo" }

it do
expect { subject }.to raise_error(NameError)
end
end
end

describe ".normalize_type" do
subject { described_class.normalize_type("Text") }

it "returns full ingredient constant name" do
is_expected.to eq("Alchemy::Ingredients::Text")
end
end

describe "#settings" do
let(:ingredient) { Alchemy::Ingredients::Text.build(role: "headline", element: element) }

Expand Down

0 comments on commit 2840cb3

Please sign in to comment.