class JSONAPI::IncludeDirective

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. @example 'posts.*' # => Include related posts, and all the included posts'

related resources.

@example 'posts.**' # => Include related posts, and all the included

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

Public Class Methods

new(include_args, options = {}) click to toggle source

@param include_args (see Parser.parse_include_args)

# 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

Public Instance Methods

[](key) click to toggle source

@param key [Symbol, String] @return [IncludeDirective, nil]

# 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) click to toggle source

@param key [Symbol, String]

# File lib/jsonapi/include_directive.rb, line 27
def key?(key)
  @hash.key?(key.to_sym) ||
    (@options[:allow_wildcard] && (@hash.key?(:*) || @hash.key?(:**)))
end
keys() click to toggle source

@return [Array<Symbol>]

# File lib/jsonapi/include_directive.rb, line 33
def keys
  @hash.keys
end
to_hash() click to toggle source

@return [Hash{Symbol => Hash}]

# 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_string() click to toggle source

@return [String]

# 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

Private Instance Methods

valid?(key) click to toggle source
# File lib/jsonapi/include_directive.rb, line 78
def valid?(key)
  key.match(valid_json_key_name_regex)
end
valid_json_key_name_regex() click to toggle source
# File lib/jsonapi/include_directive.rb, line 82
def valid_json_key_name_regex
  # https://jsonapi.org/format/#document-member-names
  /^(?![\s\-_])[\u0080-\u10FFA-Za-z0-9* _-]+(?<![\s\-_])$/
end