Module: FetcheableOnApi::Sortable

Defined in:
lib/fetcheable_on_api/sortable.rb

Overview

Sortable implements support for JSONAPI-compliant sorting via ‘sort` query parameters.

This module enables controllers to process sort parameters in the format: ‘sort=field1,-field2,+field3` where:

  • No prefix or ‘+` prefix means ascending order

  • ‘-` prefix means descending order

  • Multiple fields are comma-separated and applied in order

It supports:

  • Single and multiple field sorting

  • Ascending and descending sort directions

  • Association sorting with custom class names

  • Case-insensitive sorting with the ‘lower` option

  • Field aliasing for different database column names

Examples:

Basic sorting setup

class UsersController < ApplicationController
  sort_by :name, :email, :created_at

  def index
    users = apply_fetcheable(User.all)
    render json: users
  end
end

# GET /users?sort=name,-created_at (name asc, created_at desc)

Association sorting

class PostsController < ApplicationController
  sort_by :title, :created_at
  sort_by :author, class_name: User, as: 'name'

  def index
    posts = apply_fetcheable(Post.joins(:author))
    render json: posts
  end
end

# GET /posts?sort=author,-created_at (by author name asc, then created_at desc)

Case-insensitive sorting

class UsersController < ApplicationController
  sort_by :name, lower: true  # Sort by lowercase name
  sort_by :email, :created_at

  def index
    users = apply_fetcheable(User.all)
    render json: users
  end
end

# GET /users?sort=name (sorts by LOWER(users.name))

See Also:

Since:

  • 0.1.0

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

SORT_ORDER =

Maps sort direction prefixes to Arel sort methods. Used to parse the sort parameter and determine ascending vs descending order.

Examples:

# "+name" or "name" -> :asc (ascending)
# "-name" -> :desc (descending)

Since:

  • 0.1.0

{
  '+' => :asc,   # Explicit ascending (same as no prefix)
  '-' => :desc,  # Explicit descending
}.freeze

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Hook called when Sortable is included in a class. Sets up the class to support sort configuration and provides the sort_by class method.

Parameters:

  • base (Class)

    The class including this module

Since:

  • 0.1.0



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

def self.included(base)
  base.class_eval do
    extend ClassMethods
    # Store sort configurations per class to avoid conflicts between controllers
    class_attribute :sorts_configuration, instance_writer: false
    self.sorts_configuration = {}
  end
end