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' => { alias_name: '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

#current_action_sort_valueWarped::Sort::Value

Returns The current sort value.

Returns:



100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/warped/controllers/sortable.rb', line 100

def current_action_sort_value
  @current_action_sort_value ||= begin
    sort_obj = current_action_sorts.find do |sort|
      params[:sort_key] == sort.parameter_name
    end

    if sort_obj.present?
      Sort::Value.new(sort_obj, params[:sort_direction] || default_sort_direction)
    else
      Sort::Value.new(default_sort, default_sort_direction)
    end
  end
end

#sort(scope, sort_conditions: nil) ⇒ ActiveRecord::Relation

Parameters:

  • scope (ActiveRecord::Relation)

    The scope to sort.

  • sort_conditions (Array<Warped::Sort::Base>|nil) (defaults to: nil)

    The sort conditions.

Returns:

  • (ActiveRecord::Relation)


91
92
93
94
95
96
97
# File 'lib/warped/controllers/sortable.rb', line 91

def sort(scope, sort_conditions: nil)
  action_sorts = sort_conditions.presence || sorts
  @current_action_sorts = action_sorts

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