main
rb 43 lines 1.16 KB
Raw
1 # frozen_string_literal: true
2
3 module Admin
4 # Search / filter / paginate users for the admin users index. Encapsulates the
5 # query so the controller is a one-liner and the behaviour is unit-testable
6 # without HTTP. Instantiate with the request params.
7 class UserSearch
8 PER_PAGE = 30
9
10 attr_reader :query, :filter, :page
11
12 def initialize(params)
13 @query = params[:q].to_s.strip
14 @filter = params[:filter].presence
15 @page = [ params[:page].to_i, 1 ].max
16 end
17
18 def records
19 @records ||= scope.includes(:subscription)
20 .order(created_at: :desc)
21 .limit(PER_PAGE)
22 .offset((page - 1) * PER_PAGE)
23 .to_a
24 end
25
26 def total = @total ||= scope.count
27 def has_next? = page * PER_PAGE < total
28 def per_page = PER_PAGE
29 def admins_only? = filter == "admins"
30
31 private
32
33 def scope
34 s = User.all
35 s = s.admins if admins_only?
36 if query.present?
37 like = "%#{User.sanitize_sql_like(query)}%"
38 s = s.where("username ILIKE :q OR email ILIKE :q OR display_name ILIKE :q", q: like)
39 end
40 s
41 end
42 end
43 end