Class: Yaqb::QueryBuilders::Sort

Inherits:
Object
  • Object
show all
Defined in:
lib/yaqb/query_builders/sort.rb

Constant Summary collapse

DIRECTIONS =
%w[asc desc].freeze

Instance Method Summary collapse

Constructor Details

#initialize(scope, params, presenter) ⇒ Sort

Returns a new instance of Sort.



8
9
10
11
12
13
# File 'lib/yaqb/query_builders/sort.rb', line 8

def initialize(scope, params, presenter)
  @scope = scope
  @presenter = presenter
  @column = params[:sort]
  @direction = params[:dir]
end

Instance Method Details

#sortObject



15
16
17
18
19
20
21
22
# File 'lib/yaqb/query_builders/sort.rb', line 15

def sort
  return @scope unless @column && @direction

  validate!('sort', @column) unless @presenter.sort_attributes.include?(@column)
  validate!('dir', @direction) unless DIRECTIONS.include?(@direction)

  @scope.order(Arel.sql("#{@column} #{@direction}"))
end