From 439126ede7abbc052e9580019c3b758b2bc4af65 Mon Sep 17 00:00:00 2001 From: Thomas von Deyen Date: Fri, 1 Nov 2019 22:55:36 +0100 Subject: [PATCH] Add a rake task to convert page trees into menus Run this task to convert your current page trees into menus rake alchemy:convert:page_trees:to_menus --- lib/tasks/alchemy/convert.rake | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/lib/tasks/alchemy/convert.rake b/lib/tasks/alchemy/convert.rake index be1ded824b..86921f8ede 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 + ) + print "." + if has_children + convert_to_nodes(page.children, node: new_node) + end + 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