debian-mirror-gitlab/app/models/wiki_directory.rb

69 lines
1.9 KiB
Ruby
Raw Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
class WikiDirectory
include ActiveModel::Validations
2021-01-03 14:25:43 +05:30
attr_accessor :slug, :entries
2017-08-17 22:00:37 +05:30
validates :slug, presence: true
2023-04-23 21:23:45 +05:30
alias_method :to_param, :slug
2023-05-27 22:25:52 +05:30
class << self
# Groups a list of wiki pages into a nested collection of WikiPage and WikiDirectory objects,
# preserving the order of the passed pages.
#
# Returns an array with all entries for the toplevel directory.
#
# @param [Array<WikiPage>] pages
# @return [Array<WikiPage, WikiDirectory>]
#
def group_pages(pages)
# Build a hash to map paths to created WikiDirectory objects,
# and recursively create them for each level of the path.
# For the toplevel directory we use '' as path, as that's what WikiPage#directory returns.
directories = Hash.new do |_, path|
directories[path] = new(path).tap do |directory|
if path.present?
parent = File.dirname(path)
parent = '' if parent == '.'
directories[parent].entries << directory
directories[parent].entries.delete_if do |item|
item.is_a?(WikiPage) && item.slug.casecmp?(directory.slug)
end
end
2021-01-03 14:25:43 +05:30
end
end
2023-05-27 22:25:52 +05:30
pages.each do |page|
next unless directory_for_page?(directories[page.directory], page)
directories[page.directory].entries << page
end
directories[''].entries
2021-01-03 14:25:43 +05:30
end
2023-05-27 22:25:52 +05:30
private
def directory_for_page?(directory, page)
directory.entries.none? do |item|
item.is_a?(WikiDirectory) && item.slug.casecmp?(page.slug)
end
end
2021-01-03 14:25:43 +05:30
end
def initialize(slug, entries = [])
2017-08-17 22:00:37 +05:30
@slug = slug
2021-01-03 14:25:43 +05:30
@entries = entries
end
def title
WikiPage.unhyphenize(File.basename(slug))
2017-08-17 22:00:37 +05:30
end
# Relative path to the partial to be used when rendering collections
# of this object.
def to_partial_path
2023-04-23 21:23:45 +05:30
'shared/wikis/wiki_directory'
2017-08-17 22:00:37 +05:30
end
end