Created
May 21, 2020 18:00
-
-
Save adamstrickland/20dcf98df3e3cf558a20aa4a1c7ab968 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserSearchService | |
def initialize(search_term, limit = nil, offset = nil) | |
@search_term = if search_term.is_a?(String) | |
search_term.split(" ") | |
else | |
search_term.values.reject(&:blank?) | |
end | |
@limit = limit | |
@offset = offset | |
end | |
def call | |
if @limit.present? || @offset.present? | |
paginated_results(@limit || 0, @offset || 0) | |
else | |
complete_results | |
end | |
end | |
alias_method :search_users, :call | |
private | |
attr_reader :search_term | |
def paginated_results(limit, offset) | |
paginated_query = base_query.tap do |q| | |
q.limit(limit) if limit.positive? | |
end.tap do |q| | |
q.offset(offset) if offset.positive? | |
end | |
user_results = paginated_query.to_a | |
user_result_count = user_results.count | |
address_user_results = if limit.zero? || user_result_count < limit | |
address_query(*user_results.map(&:id)).tap do |q| | |
q.limit(limit - users_count) if limit.positive? | |
end.tap do |q| | |
q.offset(offset - users_count) if offset.positive? && users_count < offset | |
end.map(&:user) | |
else | |
[] | |
end | |
user_results + address_user_results | |
end | |
def complete_results | |
user_results = base_query.to_a | |
address_user_results = address_query(*user_results.map(&:id)).map(&:user) | |
user_results + address_user_results | |
end | |
def full_text_search_term | |
search_term.map { |t| "#{t}:*" }.join(" & ") | |
end | |
def base_query | |
Spree::User.quick_search(full_text_search_term) | |
end | |
def address_query(*user_ids) | |
Spree::Address | |
.includes(:user) | |
.where("user_id NOT IN (?)", user_ids << 0) | |
.where("user_id IS NOT NULL") | |
.quick_search(full_text_search_term) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment