class SimpleJsonapi::Parameters::SortSpec

Represents the sort parameter as defined by the JSONAPI spec.

Public Class Methods

new(specs = {}) click to toggle source

@param specs [Hash{Symbol => String},Hash{Symbol => Array<String>}]

e.g., { comments: "-date,author" }
# File lib/simple_jsonapi/parameters/sort_spec.rb, line 26
def initialize(specs = {})
  @not_supported = nil
  @data = Hash.new { |_h, _k| [] }
  merge(specs) if specs.present?
end
not_supported() click to toggle source

Creates a {SortSpec} that raises an error when it's called. @return [SortSpec]

# File lib/simple_jsonapi/parameters/sort_spec.rb, line 16
def self.not_supported
  @not_supported ||= new.tap do |spec|
    spec.instance_variable_set(:@not_supported, true)
  end
end
wrap(sorts) click to toggle source

Wraps a sort parameter in a {SortSpec} instance. @param sorts [SortSpec,Hash{Symbol => String},Hash{Symbol => Array<String>}]

# File lib/simple_jsonapi/parameters/sort_spec.rb, line 6
def self.wrap(sorts)
  if sorts.is_a?(SortSpec)
    sorts
  else
    SortSpec.new(sorts)
  end
end

Public Instance Methods

[](relationship_name) click to toggle source

@param relationship_name [String,Symbol] @return [SortFieldSpec]

# File lib/simple_jsonapi/parameters/sort_spec.rb, line 48
def [](relationship_name)
  if not_supported?
    raise NotImplementedError, "Sorting nested relationships is not implemented."
  else
    @data[relationship_name.to_sym]
  end
end
merge(specs = {}) click to toggle source

@param specs [Hash{Symbol => String},Hash{Symbol => Array<String>}]

e.g., { comments: "-date,author" } or { comments: ["-date", "author"] }

@return [self]

# File lib/simple_jsonapi/parameters/sort_spec.rb, line 35
def merge(specs = {})
  specs.each do |relationship_name, field_specs|
    @data[relationship_name.to_sym] = Array
                                      .wrap(field_specs)
                                      .flat_map { |fs| fs.to_s.split(",") }
                                      .map { |fs| SortFieldSpec.new(fs) }
                                      .presence
  end
  self
end

Protected Instance Methods

not_supported?() click to toggle source
# File lib/simple_jsonapi/parameters/sort_spec.rb, line 58
def not_supported?
  !!@not_supported
end