2020-03-12 13:20:56 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
##
|
|
|
|
# Allows us to query Bookmark records for lists. Used mainly
|
|
|
|
# in the user/activity/bookmarks page.
|
|
|
|
|
|
|
|
class BookmarkQuery
|
2020-03-19 13:48:23 +08:00
|
|
|
cattr_accessor :preloaded_custom_fields
|
|
|
|
self.preloaded_custom_fields = Set.new
|
|
|
|
|
|
|
|
def self.on_preload(&blk)
|
|
|
|
(@preload ||= Set.new) << blk
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.preload(bookmarks, object)
|
|
|
|
if @preload
|
|
|
|
@preload.each { |preload| preload.call(bookmarks, object) }
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-03-13 08:44:39 +08:00
|
|
|
def initialize(user, params = {})
|
2020-03-12 13:20:56 +08:00
|
|
|
@user = user
|
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
|
|
|
def list_all
|
|
|
|
results = user_bookmarks
|
|
|
|
.joins('INNER JOIN topics ON topics.id = bookmarks.topic_id')
|
|
|
|
.joins('INNER JOIN posts ON posts.id = bookmarks.post_id')
|
|
|
|
.joins('INNER JOIN users ON users.id = posts.user_id')
|
2020-03-19 13:48:23 +08:00
|
|
|
.order('bookmarks.created_at DESC')
|
2020-03-12 13:20:56 +08:00
|
|
|
|
|
|
|
if @params[:limit]
|
|
|
|
results = results.limit(@params[:limit])
|
|
|
|
end
|
|
|
|
|
2020-03-19 13:48:23 +08:00
|
|
|
if BookmarkQuery.preloaded_custom_fields.any?
|
|
|
|
Topic.preload_custom_fields(
|
|
|
|
results.map(&:topic), BookmarkQuery.preloaded_custom_fields
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
BookmarkQuery.preload(results, self)
|
|
|
|
|
2020-03-12 13:20:56 +08:00
|
|
|
results
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def user_bookmarks
|
2020-03-19 13:48:23 +08:00
|
|
|
Bookmark.where(user: @user)
|
|
|
|
.includes(topic: :tags)
|
|
|
|
.includes(post: :user)
|
2020-03-12 13:20:56 +08:00
|
|
|
end
|
|
|
|
end
|