Skip to content

Commit

Permalink
Add a rake task to convert page trees into menus
Browse files Browse the repository at this point in the history
Run this task to convert your current page trees into menus

    rake alchemy:convert:page_trees:to_menus
  • Loading branch information
tvdeyen committed Nov 5, 2019
1 parent 45d29a5 commit 608b865
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions lib/tasks/alchemy/convert.rake
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,44 @@ namespace :alchemy do
puts "Done."
end
end

namespace :page_trees do
desc "Converts the page tree into a menu."
task to_menus: [:environment] do
if Alchemy::Node.roots.exists?
abort "\n⨯ There are already menus present in your database. Aborting!"
end

def convert_to_nodes(children, node:)
children.each do |page|
has_children = page.children.any?
next unless page.visible || has_children

new_node = node.children.create!(
name: page.visible? ? nil : page.name,
page: page.visible? ? page : nil,
language_id: page.language_id
)
print "."
if has_children
convert_to_nodes(page.children, node: new_node)
end
end
end

puts "\n- Converting page trees into menus. Hold tight, this may take a while!"
Alchemy::BaseRecord.transaction do
Alchemy::Language.all.each do |language|
locale = language.locale.presence || I18n.default_locale
menu_name = I18n.t('Main Navigation', scope: 'alchemy.menu_names', default: 'Main Navigation', locale: locale)
root_node = Alchemy::Node.create(language: language, name: menu_name)
language.pages.language_roots.each do |root_page|
convert_to_nodes(root_page.children, node: root_node)
end
end
end
puts "\n✓ Done."
end
end
end
end

0 comments on commit 608b865

Please sign in to comment.