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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of IncludeDirective.


16
17
18
19
20
21
22
# 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|
    hash[key] = self.class.new(value, options)
  end
  @options = options
end

Instance Method Details

#[](key) ⇒ IncludeDirective?

Parameters:

  • key (Symbol, String)

Returns:


32
33
34
35
36
37
38
39
40
41
# File 'lib/jsonapi/include_directive.rb', line 32

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)

25
26
27
28
# File 'lib/jsonapi/include_directive.rb', line 25

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

#to_hashHash{Symbol => Hash}

Returns:

  • (Hash{Symbol => Hash})

44
45
46
47
48
# File 'lib/jsonapi/include_directive.rb', line 44

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

#to_stringString

Returns:

  • (String)

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/jsonapi/include_directive.rb', line 51

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