Class: AgentCode::QueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/agentcode/query_builder.rb

Overview

Custom query builder that provides AgentCode's exact URL parameter format. Replaces Spatie QueryBuilder for Rails.

Supports:

  • Filtering: ?filter=published&filter=1
  • Sorting: ?sort=-created_at,title
  • Search: ?search=term
  • Pagination: ?page=1&per_page=20
  • Fields: ?fields=id,title,status
  • Includes: ?include=user,comments

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, params: {}) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



17
18
19
20
21
# File 'lib/agentcode/query_builder.rb', line 17

def initialize(model_class, params: {})
  @model_class = model_class
  @scope = model_class.all
  @params = params
end

Instance Attribute Details

#model_classObject (readonly)

Returns the value of attribute model_class.



15
16
17
# File 'lib/agentcode/query_builder.rb', line 15

def model_class
  @model_class
end

#paramsObject (readonly)

Returns the value of attribute params.



15
16
17
# File 'lib/agentcode/query_builder.rb', line 15

def params
  @params
end

#scopeObject (readonly)

Returns the value of attribute scope.



15
16
17
# File 'lib/agentcode/query_builder.rb', line 15

def scope
  @scope
end

Instance Method Details

#buildObject

Apply all query modifications based on params and model config.



24
25
26
27
28
29
30
31
32
# File 'lib/agentcode/query_builder.rb', line 24

def build
  apply_filters
  apply_default_sort
  apply_sorts
  apply_search
  apply_fields
  apply_includes
  self
end

#paginate(per_page: nil, page: nil) ⇒ Object

Execute with pagination. Returns { items:, pagination: }.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/agentcode/query_builder.rb', line 40

def paginate(per_page: nil, page: nil)
  per_page = (per_page || params[:per_page] || model_class.try(:agentcode_per_page_count) || 25).to_i
  per_page = [[per_page, 1].max, 100].min # clamp between 1 and 100
  page = (page || params[:page] || 1).to_i
  page = [page, 1].max

  total = @scope.count
  last_page = (total.to_f / per_page).ceil
  last_page = [last_page, 1].max

  items = @scope.offset((page - 1) * per_page).limit(per_page)

  {
    items: items,
    pagination: {
      current_page: page,
      last_page: last_page,
      per_page: per_page,
      total: total
    }
  }
end

#to_scopeObject

Get the final ActiveRecord relation.



35
36
37
# File 'lib/agentcode/query_builder.rb', line 35

def to_scope
  @scope
end