Class: SimpleJsonapi::Parameters::FieldsSpec

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

Overview

Represents the fields parameter as defined by the JSONAPI spec.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(specs = {}) ⇒ FieldsSpec

Returns a new instance of FieldsSpec.

Parameters:

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

    The hash keys are resource types, and the values are lists of field names to render in the output.



16
17
18
19
# File 'lib/simple_jsonapi/parameters/fields_spec.rb', line 16

def initialize(specs = {})
  @data = {}
  merge(specs) if specs.present?
end

Class Method Details

.wrap(fields) ⇒ Object

Wraps a fields parameter in a SimpleJsonapi::Parameters::FieldsSpec instance.

Parameters:



6
7
8
9
10
11
12
# File 'lib/simple_jsonapi/parameters/fields_spec.rb', line 6

def self.wrap(fields)
  if fields.is_a?(FieldsSpec)
    fields
  else
    FieldsSpec.new(fields)
  end
end

Instance Method Details

#[](type) ⇒ Array<Symbol>

Parameters:

  • type (String, Symbol)

Returns:

  • (Array<Symbol>)


36
37
38
# File 'lib/simple_jsonapi/parameters/fields_spec.rb', line 36

def [](type)
  @data[type.to_sym]
end

#all_fields?(type) ⇒ Boolean

Parameters:

  • type (String, Symbol)

Returns:

  • (Boolean)


41
42
43
# File 'lib/simple_jsonapi/parameters/fields_spec.rb', line 41

def all_fields?(type)
  @data[type.to_sym].nil?
end

#merge(specs = {}) ⇒ self

Parameters:

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

    The hash keys are resource types, and the values are lists of field names to render in the output.

Returns:

  • (self)


24
25
26
27
28
29
30
31
32
# File 'lib/simple_jsonapi/parameters/fields_spec.rb', line 24

def merge(specs = {})
  specs.each do |type, fields|
    @data[type.to_sym] = Array
                         .wrap(fields)
                         .flat_map { |s| s.to_s.split(",") }
                         .map { |s| s.strip.to_sym }
  end
  self
end