| 1 | # frozen_string_literal: true |
| 2 | |
| 3 | module Admin |
| 4 | # Search / filter / paginate the repository catalog for the admin repos index. |
| 5 | class RepositorySearch |
| 6 | PER_PAGE = 30 |
| 7 | |
| 8 | attr_reader :query, :kind, :filter, :page |
| 9 | |
| 10 | def initialize(params) |
| 11 | @query = params[:q].to_s.strip |
| 12 | @kind = params[:kind].presence |
| 13 | @filter = params[:filter].presence |
| 14 | @page = [ params[:page].to_i, 1 ].max |
| 15 | end |
| 16 | |
| 17 | def records |
| 18 | @records ||= scope.order(created_at: :desc) |
| 19 | .limit(PER_PAGE) |
| 20 | .offset((page - 1) * PER_PAGE) |
| 21 | .to_a |
| 22 | end |
| 23 | |
| 24 | def total = @total ||= scope.count |
| 25 | def has_next? = page * PER_PAGE < total |
| 26 | def per_page = PER_PAGE |
| 27 | def private_only? = filter == "private" |
| 28 | |
| 29 | private |
| 30 | |
| 31 | def scope |
| 32 | s = Repository.includes(:user) |
| 33 | s = s.where(kind: kind) if %w[code model].include?(kind) |
| 34 | s = s.where(is_private: true) if private_only? |
| 35 | if query.present? |
| 36 | like = "%#{Repository.sanitize_sql_like(query)}%" |
| 37 | s = s.where("repositories.name ILIKE :q OR repositories.description ILIKE :q", q: like) |
| 38 | end |
| 39 | s |
| 40 | end |
| 41 | end |
| 42 | end |