Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extract element ingredient migrator #2337

Merged
merged 2 commits into from
May 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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