Skip to content

Commit

Permalink
Merge pull request #2337 from tvdeyen/extract-element-ingredient-migr…
Browse files Browse the repository at this point in the history
…ator

Extract element ingredient migrator
  • Loading branch information
tvdeyen committed May 11, 2022
1 parent f8329c6 commit dca5b3f
Showing 1 changed file with 35 additions and 25 deletions.
60 changes: 35 additions & 25 deletions lib/alchemy/upgrader/tasks/ingredients_migrator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,31 +24,8 @@ def create_ingredients
if elements.any?
puts "-- Creating ingredients for #{elements.count} #{element_definition[:name]}(s)"
elements.each do |element|
Alchemy::Element.transaction do
element_definition[:ingredients].each do |ingredient_definition|
content = element.content_by_name(ingredient_definition[:role])
next unless content

essence = content.essence
ingredient = element.ingredients.build(
role: ingredient_definition[:role],
type: Alchemy::Ingredient.normalize_type(ingredient_definition[:type]),
)
belongs_to_associations = essence.class.reflect_on_all_associations(:belongs_to)
if belongs_to_associations.any?
ingredient.related_object = essence.public_send(belongs_to_associations.first.name)
else
ingredient.value = content.ingredient
end
data = ingredient.class.stored_attributes.fetch(:data, []).each_with_object({}) do |attr, d|
d[attr] = essence.public_send(attr)
end
ingredient.data = data
print "."
ingredient.save!
content.destroy!
end
end
MigrateElementIngredients.call(element)
print "."
end
puts "\n"
else
Expand All @@ -58,5 +35,38 @@ def create_ingredients
end
end
end

class MigrateElementIngredients
def self.call(element)
Alchemy::Element.transaction do
element.definition[:ingredients].each do |ingredient_definition|
ingredient = element.ingredients.build(
role: ingredient_definition[:role],
type: Alchemy::Ingredient.normalize_type(ingredient_definition[:type]),
)

content = element.content_by_name(ingredient_definition[:role])
if content
essence = content.essence
if essence
belongs_to_associations = essence.class.reflect_on_all_associations(:belongs_to)
if belongs_to_associations.any?
ingredient.related_object = essence.public_send(belongs_to_associations.first.name)
else
ingredient.value = content.ingredient
end
data = ingredient.class.stored_attributes.fetch(:data, []).each_with_object({}) do |attr, d|
d[attr] = essence.public_send(attr)
end
ingredient.data = data
end
content.destroy!
end

ingredient.save!
end
end
end
end
end
end

0 comments on commit dca5b3f

Please sign in to comment.