class JsonApiServer::SortConfigs

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.sort_options = {
  permitted: [
    :id,
    :body,
    { created: { col_name: :created_at} }
  ],
  default: { id: :desc }
}

end

Config requirements - :permitted, :col_name and :default must be symbols.

Public Class Methods

new(configs) click to toggle source

Config - permitted

# File lib/json_api_server/sort_configs.rb, line 22
def initialize(configs)
  @configs = configs
end

Public Instance Methods

config_for(attr) click to toggle source

Returns the config spec for an attributes. Returns nil if attribute isn't permitted.

# 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() click to toggle source

Default order specified in 'options' accessor. Specify ActiveRecord order params, i.e., { id: :desc } Defaults to empty array if none specified.

# File lib/json_api_server/sort_configs.rb, line 48
def default_order
  @default = @configs[:default] || []
end
permitted() click to toggle source

Attributes API users can sort against. Arrray of hashes -

{attr: <required - attr as string>, col_name: <optional key - database column name as string> }, …
# 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) click to toggle source
# File lib/json_api_server/sort_configs.rb, line 41
def permitted?(attr)
  config_for(attr.to_s) != nil
end

Protected Instance Methods

configs_from(config) click to toggle source
# File lib/json_api_server/sort_configs.rb, line 54
def configs_from(config)
  if config.respond_to?(:keys)
    key, value = config.first
    { attr: key.to_s, col_name: (value[:col_name] || key).to_s }
  else
    { attr: config.to_s }
  end
end