Class: JSONAPI::IncludeDirective

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi/include_directive.rb,
lib/jsonapi/include_directive/parser.rb

Overview

Represent a recursive set of include directives (c.f. jsonapi.org/format/#fetching-includes)

Addition to the spec: two wildcards, namely ‘*’ and ‘**’. The former stands for any one level of relationship, and the latter stands for any number of levels of relationships.

Examples:

‘posts.*’ # => Include related posts, and all the included posts’

related resources.

‘posts.**’ # => Include related posts, and all the included

posts' related resources, and their related resources, recursively.

Defined Under Namespace

Modules: Parser Classes: InvalidKey

Instance Method Summary collapse

Constructor Details

#initialize(include_args, options = {}) ⇒ IncludeDirective

Returns a new instance of IncludeDirective.



16
17
18
19
20
21
22
23
24
# File 'lib/jsonapi/include_directive.rb', line 16

def initialize(include_args, options = {})
  include_hash = Parser.parse_include_args(include_args)
  @hash = include_hash.each_with_object({}) do |(key, value), hash|
    raise InvalidKey, key unless valid?(key)

    hash[key] = self.class.new(value, options)
  end
  @options = options
end

Instance Method Details

#[](key) ⇒ IncludeDirective?

Parameters:

  • key (Symbol, String)

Returns:



39
40
41
42
43
44
45
46
47
48
# File 'lib/jsonapi/include_directive.rb', line 39

def [](key)
  case
  when @hash.key?(key.to_sym)
    @hash[key.to_sym]
  when @options[:allow_wildcard] && @hash.key?(:**)
    self.class.new({ :** => {} }, @options)
  when @options[:allow_wildcard] && @hash.key?(:*)
    @hash[:*]
  end
end

#key?(key) ⇒ Boolean

Parameters:

  • key (Symbol, String)

Returns:

  • (Boolean)


27
28
29
30
# File 'lib/jsonapi/include_directive.rb', line 27

def key?(key)
  @hash.key?(key.to_sym) ||
    (@options[:allow_wildcard] && (@hash.key?(:*) || @hash.key?(:**)))
end

#keysArray<Symbol>

Returns:

  • (Array<Symbol>)


33
34
35
# File 'lib/jsonapi/include_directive.rb', line 33

def keys
  @hash.keys
end

#to_hashHash{Symbol => Hash}

Returns:

  • (Hash{Symbol => Hash})


51
52
53
54
55
# File 'lib/jsonapi/include_directive.rb', line 51

def to_hash
  @hash.each_with_object({}) do |(key, value), hash|
    hash[key] = value.to_hash
  end
end

#to_stringString

Returns:

  • (String)


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/jsonapi/include_directive.rb', line 58

def to_string
  string_array = @hash.map do |(key, value)|
    string_value = value.to_string
    if string_value == ''
      key.to_s
    else
      string_value
        .split(',')
        .map { |x| key.to_s + '.' + x }
        .join(',')
    end
  end

  string_array.join(',')
end