Module: APIResourceSortable

Extended by:
ActiveSupport::Concern
Included in:
API::APIDataManagement, API::Open, API::V1
Defined in:
app/api/concerns/api_resource_sortable.rb

Overview

Helper To Make Resource APIs Sortable

A Sortable Resource API gives the flexibility to change how the returned data is sorted to the client. Clients can use the sort URL parameter to control how the returned data is sorted, as this example:

GET /posts?sort=-created_at,title

This means to sort the data by its created time descended and then the title ascended.

Usage

Include this Concern in your Grape API class:

class SampleAPI < Grape::API
  include APIResourceSortable
end

then use the sortable method like this:

resources :posts do
  get do
    sortable default_order: {created_at: :desc }    # ...

    @posts = Post.order(sort)#...
    # ...
  end
end

Defined Under Namespace

Modules: HelperMethods

Class Method Summary collapse

Class Method Details

.sort_param_desc(example: nil, default: nil) ⇒ Object

Return the 'sort' param description


75
76
77
78
79
80
81
82
83
84
85
86
# File 'app/api/concerns/api_resource_sortable.rb', line 75

def self.sort_param_desc(example: nil, default: nil)
  if default.present?
    desc = "Specify how the returning data should be sorted, defaults to '#{default}'."
  else
    desc = "Specify how the returning data should be sorted."
  end
  if example.present?
    "#{desc} Example value: '#{example}'"
  else
    desc
  end
end