Class: JsonApiServer::SortConfigs
- Inherits:
-
Object
- Object
- JsonApiServer::SortConfigs
- Defined in:
- lib/json_api_server/sort_configs.rb
Overview
Configs that can be specified in a controller to enable sorting on attributes. Specify permitted attributes for sorting. If an alias is used instead of an attribute name, it can be mapped (see :created in example below).
Example sort configuration:
before_action do |c|
c. = {
permitted: [
:id,
:body,
{ created: { col_name: :created_at} }
],
default: { id: :desc }
}
end
Config requirements - :permitted, :col_name and :default must be symbols.
Instance Method Summary collapse
-
#config_for(attr) ⇒ Object
Returns the config spec for an attributes.
-
#default_order ⇒ Object
Default order specified in ‘options’ accessor.
-
#initialize(configs) ⇒ SortConfigs
constructor
Config - permitted.
-
#permitted ⇒ Object
Attributes API users can sort against.
- #permitted?(attr) ⇒ Boolean
Constructor Details
#initialize(configs) ⇒ SortConfigs
Config - permitted
22 23 24 |
# File 'lib/json_api_server/sort_configs.rb', line 22 def initialize(configs) @configs = configs end |
Instance Method Details
#config_for(attr) ⇒ Object
Returns the config spec for an attributes. Returns nil if attribute isn’t permitted.
37 38 39 |
# File 'lib/json_api_server/sort_configs.rb', line 37 def config_for(attr) permitted.find { |elem| elem[:attr] == attr.to_s } end |
#default_order ⇒ Object
Default order specified in ‘options’ accessor. Specify ActiveRecord order params, i.e., { id: :desc } Defaults to empty array if none specified.
48 49 50 |
# File 'lib/json_api_server/sort_configs.rb', line 48 def default_order @default = @configs[:default] || [] end |
#permitted ⇒ Object
Attributes API users can sort against. Arrray of hashes -
- {attr: <required - attr as string>, col_name: <optional key - database column name as string> }, …
28 29 30 31 32 33 |
# File 'lib/json_api_server/sort_configs.rb', line 28 def permitted @permitted ||= begin return [] unless @configs[:permitted].is_a?(Array) @configs[:permitted].map { |c| configs_from(c) } end end |
#permitted?(attr) ⇒ Boolean
41 42 43 |
# File 'lib/json_api_server/sort_configs.rb', line 41 def permitted?(attr) config_for(attr.to_s) != nil end |