Module: Warped::Controllers::Sortable

Extended by:
ActiveSupport::Concern
Included in:
Ui, Tabulatable
Defined in:
lib/warped/controllers/sortable.rb,
lib/warped/controllers/sortable/ui.rb

Overview

Provides functionality for sorting records from an ActiveRecord::Relation in a controller.

Example usage:

class UsersController < ApplicationController
  include Sortable

  sortable_by :name, :created_at, 'accounts.kind'

  def index
    scope = sort(User.joins(:account))
    render json: scope
  end
end

Example requests:

GET /users?sort_key=name
GET /users?sort_key=name&sort_direction=asc_nulls_first
GET /users?sort_key=created_at&sort_direction=asc

Renaming sort keys:

In some cases, you may not want to expose the actual column names to the client. In such cases, you can rename the sort keys by passing a hash to the sortable_by method.

Example:

class UsersController < ApplicationController
  include Sortable

  sortable_by :name, :created_at, 'accounts.referrals_count' => 'referrals'

  def index
    scope = sort(User.joins(:account))
    render json: scope
  end
end

Example requests:

GET /users?sort_key=referrals&sort_direction=asc

The sort_key and sort_direction parameters are optional. If not provided, the default sort key and direction will be used.

The default sort key and sort direction can be set at a controller level using the default_sort_direction and default_sort_key class attributes.

Defined Under Namespace

Modules: Ui

Instance Method Summary collapse

Instance Method Details

#sort(scope, sort_key: self.sort_key, sort_direction: self.sort_direction) ⇒ ActiveRecord::Relation

Parameters:

  • scope (ActiveRecord::Relation)

    The scope to sort.

  • sort_key (String, Symbol) (defaults to: self.sort_key)

    The sort key.

  • sort_direction (String, Symbol) (defaults to: self.sort_direction)

    The sort direction.

Returns:

  • (ActiveRecord::Relation)


77
78
79
80
81
82
83
# File 'lib/warped/controllers/sortable.rb', line 77

def sort(scope, sort_key: self.sort_key, sort_direction: self.sort_direction)
  return scope unless sort_key && sort_direction

  validate_sort_key!

  Queries::Sort.call(scope, sort_key:, sort_direction:)
end