Class: SimpleJsonapi::Parameters::SortSpec

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_jsonapi/parameters/sort_spec.rb

Overview

Represents the sort parameter as defined by the JSONAPI spec.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(specs = {}) ⇒ SortSpec

Returns a new instance of SortSpec.

Parameters:

  • specs (Hash{Symbol => String}, Hash{Symbol => Array<String>}) (defaults to: {})

    e.g., { comments: “-date,author” }



26
27
28
29
30
# 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

Class Method Details

.not_supportedSortSpec

Creates a SimpleJsonapi::Parameters::SortSpec that raises an error when it’s called.

Returns:



16
17
18
19
20
# 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) ⇒ Object

Wraps a sort parameter in a SimpleJsonapi::Parameters::SortSpec instance.

Parameters:

  • sorts (SortSpec, Hash{Symbol => String}, Hash{Symbol => Array<String>})


6
7
8
9
10
11
12
# 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

Instance Method Details

#[](relationship_name) ⇒ SortFieldSpec

Parameters:

  • relationship_name (String, Symbol)

Returns:



48
49
50
51
52
53
54
# 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 = {}) ⇒ self

Parameters:

  • specs (Hash{Symbol => String}, Hash{Symbol => Array<String>}) (defaults to: {})

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

Returns:

  • (self)


35
36
37
38
39
40
41
42
43
44
# 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