Method: Caprese::Query#apply_sorting_pagination_to_scope

Defined in:
lib/caprese/controller/concerns/query.rb

#apply_sorting_pagination_to_scope(scope) ⇒ Relation

Applies query_params and query_params to a given scope

Parameters:

  • scope (Relation)

    the scope to apply sorting and pagination to

Returns:

  • (Relation)

    the sorted and paginated scope



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/caprese/controller/concerns/query.rb', line 161

def apply_sorting_pagination_to_scope(scope)
  return scope if scope.empty?

  if query_params[:sort].try(:any?)
    ordering = {}
    query_params[:sort].each do |sort_field|
      ordering = ordering.merge(
        if sort_field[0] == '-' # EX: -created_at, sort by created_at descending
          { actual_field(sort_field[1..-1]) => :desc }
        else
          { actual_field(sort_field) => :asc }
        end
      )
    end
    scope = scope.reorder(ordering)
  end

  if query_params[:offset] || query_params[:limit]
    offset = query_params[:offset].to_i || 0

    if offset < 0
      offset = scope.count + offset
    end

    limit = query_params[:limit] && query_params[:limit].to_i || self.config.default_page_size
    limit = [limit, self.config.max_page_size].min

    scope.offset(offset).limit(limit)
  else
    page_number = query_params[:page].try(:[], :number)
    page_size = query_params[:page].try(:[], :size).try(:to_i) || self.config.default_page_size
    page_size = [page_size, self.config.max_page_size].min

    scope.page(page_number).per(page_size)
  end
end