diff --git a/lib/tasks/alchemy/convert.rake b/lib/tasks/alchemy/convert.rake index be1ded824b..8387116815 100644 --- a/lib/tasks/alchemy/convert.rake +++ b/lib/tasks/alchemy/convert.rake @@ -31,5 +31,48 @@ 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 + + Alchemy::Deprecation.silence do + new_node = node.children.create!( + name: page.visible? && !page.redirects_to_external? ? nil : page.name, + page: page.visible? && !page.redirects_to_external? ? page : nil, + url: page.redirects_to_external? ? page.urlname : nil, + external: page.redirects_to_external? && Alchemy::Config.get(:open_external_links_in_new_tab), + language_id: page.language_id + ) + end + print "." + if has_children + convert_to_nodes(page.children, node: new_node) + end + end + end + menu_count = Alchemy::Language.count + puts "\n- Converting #{menu_count} page #{'tree'.pluralize(menu_count)} into #{'menu'.pluralize(menu_count)}." + 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