Skip to content

Instantly share code, notes, and snippets.

@bazzel
Last active September 8, 2015 19:25
Show Gist options
  • Save bazzel/c6382a8400b03e512db5 to your computer and use it in GitHub Desktop.
Save bazzel/c6382a8400b03e512db5 to your computer and use it in GitHub Desktop.
Related posts, before and after
def similar_posts(post)
related_posts(post).tap do |posts|
(posts << @posts.first(2)).flatten!
end.first(2)
end
def related_posts(post)
categories_ids = post.categories.map(&:id)
@posts.select do |p|
p != post && (p.categories.map(&:id) & categories_ids).present?
end
end
# Limits the array to 2 elements and adds recent posts
# if there are not enough related posts
#
# @return [Array<Post>] `limit` items, somehow related to `post`
#
# @param [Post] post the object we need related posts for
# @param [Array<Post>] posts the collection to look for related posts
# @param [FixNum] limit The number of items to return
#
# @example
# post = @posts.first
# similar_posts post, @posts
def similar_posts(post, posts, limit=2)
related_posts = related_posts(post, posts)
completion = (posts - [post]).first(limit)
(related_posts | completion).first(limit)
end
# Returns an array of posts from the same category
#
# @return [Array<Post>] items somehow related to `post`
#
# @param [Post] post the object we need related posts for
# @param [Array<Post>] posts the collection to look for related posts
#
# @example
# post = @posts.first
# related_posts post, @posts
def related_posts(post, posts)
category_ids = Array(post.categories).map(&:id)
other_posts = posts - [post]
other_posts.select do |p|
next if (other_categories = p.categories).nil?
(other_categories.map(&:id) & category_ids).present?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment