Class: SimpleJsonapi::Parameters::IncludeSpec

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

Overview

Represents the include parameter as defined by the JSONAPI spec.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*specs) ⇒ IncludeSpec

Returns a new instance of IncludeSpec.

Parameters:

  • specs (String, Array<String>, Array<Symbol>)

    e.g. "author,comments,comments.author" or ["author", "comments", "comments.author"]



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

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

Class Method Details

.wrap(specs) ⇒ Object

Wraps an include parameter in an SimpleJsonapi::Parameters::IncludeSpec instance.

Parameters:

  • specs (IncludeSpec, String, Array<String>, Array<Symbol>)


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

def self.wrap(specs)
  if specs.is_a?(IncludeSpec)
    specs
  else
    IncludeSpec.new(specs)
  end
end

Instance Method Details

#[](relationship_name) ⇒ IncludeSpec

Parameters:

  • relationship_name (String, Symbol)

Returns:



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

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

#include?(relationship_name) ⇒ Boolean

Parameters:

  • relationship_name (String, Symbol)

Returns:

  • (Boolean)


46
47
48
# File 'lib/simple_jsonapi/parameters/include_spec.rb', line 46

def include?(relationship_name)
  @data.key?(relationship_name.to_sym)
end

#merge(*specs) ⇒ self

Parameters:

  • specs (String, Array<String>, Array<Symbol>)

    e.g. "author,comments,comments.author" or ["author", "comments", "comments.author"]

Returns:

  • (self)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/simple_jsonapi/parameters/include_spec.rb', line 24

def merge(*specs)
  paths = specs.flatten.flat_map { |s| s.to_s.split(",") }

  paths.each do |path|
    terms = path.split(".")

    nested_spec = @data[terms.first.to_sym] ||= IncludeSpec.new
    if terms.size > 1
      nested_spec.merge(terms.drop(1).join("."))
    end
  end

  self
end

#to_hHash

Returns:

  • (Hash)


51
52
53
54
55
# File 'lib/simple_jsonapi/parameters/include_spec.rb', line 51

def to_h
  @data.each_with_object({}) do |(name, spec), hash|
    hash[name] = spec.to_h
  end
end