Skip to content

Commit

Permalink
Create ingredient on element collection
Browse files Browse the repository at this point in the history
In the element editor with have a feature that creates ingredients
that are defined but not created yet. Before we removed the abstract
class from Ingredient we needed to create the ingredient on the class
instead of the collection. Since the collection is eager loaded it has
to be updated with the newly created ingredient in order to prevent
the ingredient to be created twice (leading to unique index violation
errors).
  • Loading branch information
tvdeyen committed Aug 12, 2021
1 parent df4115b commit aa2ccd0
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
11 changes: 7 additions & 4 deletions app/decorators/alchemy/element_editor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def contents
# @return Array<Alchemy::IngredientEditor>
def ingredients
element.definition.fetch(:ingredients, []).map do |ingredient|
Alchemy::IngredientEditor.new(find_or_create_ingredient(ingredient[:role]))
Alchemy::IngredientEditor.new(find_or_create_ingredient(ingredient))
end
end

Expand Down Expand Up @@ -121,9 +121,12 @@ def create_content(name)
Alchemy::Content.create(element: element, name: name)
end

def find_or_create_ingredient(role)
element.ingredients.find { |i| i.role == role } ||
Ingredient.create(element: element, role: role)
def find_or_create_ingredient(definition)
element.ingredients.detect { |i| i.role == definition[:role] } ||
element.ingredients.create!(
role: definition[:role],
type: Alchemy::Ingredient.normalize_type(definition[:type]),
)
end
end
end
36 changes: 36 additions & 0 deletions spec/decorators/alchemy/element_editor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,42 @@
end
end

describe "#ingredients" do
let(:element) { create(:alchemy_element, :with_ingredients) }

subject(:ingredients) { element_editor.ingredients }

it "returns a ContentEditor instance for each ingredient defined" do
aggregate_failures do
ingredients.each do |ingredient|
expect(ingredient).to be_an(Alchemy::IngredientEditor)
end
end
end

context "with a ingredient defined but not existing yet" do
let(:element) { create(:alchemy_element, name: "headline") }

before do
expect(element).to receive(:definition).at_least(:once) do
{
name: "headline",
ingredients: [
{
role: "headline",
type: "Headline",
},
],
}.with_indifferent_access
end
end

it "creates the missing ingredient" do
expect { subject }.to change { element.ingredients.count }.by(1)
end
end
end

describe "#to_partial_path" do
subject { element_editor.to_partial_path }

Expand Down

0 comments on commit aa2ccd0

Please sign in to comment.