Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return ordered results for belongs_to array #390

Merged
merged 2 commits into from
Sep 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion bridgetown-core/lib/bridgetown-core/collection.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# frozen_string_literal: true

module Bridgetown
class Collection
class Collection # rubocop:todo Metrics/ClassLength
# @return [Bridgetown::Site]
attr_reader :site

Expand Down Expand Up @@ -48,6 +48,20 @@ def resources
@resources ||= []
end

# Fetch the collection resources and arrange them by slug in a hash.
#
# @return [Hash<String, Bridgetown::Resource::Base>]
def resources_by_slug
resources.group_by { |item| item.data.slug }.transform_values(&:first)
end

# Fetch the collection resources and arrange them by relative URL in a hash.
#
# @return [Hash<String, Bridgetown::Resource::Base>]
def resources_by_relative_url
resources.group_by(&:relative_url).transform_values(&:first)
end

# Iterate over either Resources or Documents depending on how the site is
# configured
def each(&block)
Expand Down
5 changes: 2 additions & 3 deletions bridgetown-core/lib/bridgetown-core/resource/relations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,8 @@ def collection_labels
# @return [Bridgetown::Resource::Base, Array<Bridgetown::Resource::Base>]
def belongs_to_relation_for_type(type)
if resource.data[type].is_a?(Array)
other_collection_for_type(type).resources.select do |other_resource|
other_resource.data.slug.in?(resource.data[type])
end
other_slugs = other_collection_for_type(type).resources_by_slug
resource.data[type].map { |slug| other_slugs[slug] }.compact
else
other_collection_for_type(type).resources.find do |other_resource|
other_resource.data.slug == resource.data[type]
Expand Down