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 6, 2019
1 parent a2171d4 commit 439126e
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/tasks/alchemy/convert.rake
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 439126e

Please sign in to comment.