Module: FetcheableOnApi::Sortable::ClassMethods

Defined in:
lib/fetcheable_on_api/sortable.rb

Overview

Class methods made available to controllers when Sortable is included.

Since:

  • 0.1.0

Instance Method Summary collapse

Instance Method Details

#sort_by(*attrs) ⇒ Object

Define one or more sortable attributes for the controller.

This method configures which model attributes can be sorted via query parameters and how those sorts should be processed.

Examples:

Basic attribute sorting

sort_by :name, :email, :created_at
# Allows: sort=name,-email,created_at

Case-insensitive sorting

sort_by :name, lower: true
# Generates: ORDER BY LOWER(users.name)

Association sorting

sort_by :author, class_name: User, as: 'name'
# Allows: sort=author (sorts by users.name)

Association sorting with custom association name

sort_by :author_name, class_name: User, as: 'name', association: :author
# Allows: sort=author_name (sorts by users.name via author association)
# Note: Make sure your collection is joined: Book.joins(:author)

Field aliasing

sort_by :full_name, as: 'name'
# Maps sort=full_name to ORDER BY users.name

Parameters:

  • attrs (Array<Symbol>)

    List of attribute names to make sortable

  • options (Hash)

    Configuration options for the sorts

Since:

  • 0.1.0



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/fetcheable_on_api/sortable.rb', line 119

def sort_by(*attrs)
  options = attrs.extract_options!
  options.symbolize_keys!

  # Validate that only supported options are provided
  options.assert_valid_keys(:as, :class_name, :lower, :association)

  # Create a new configuration hash to avoid modifying parent class config
  self.sorts_configuration = sorts_configuration.dup

  attrs.each do |attr|
    # Initialize default configuration for this attribute
    sorts_configuration[attr] ||= {
      as: attr
    }

    # Merge in the provided options, overriding defaults
    sorts_configuration[attr] = sorts_configuration[attr].merge(options)
  end
end