Sha256: 8a6aaf6d7da50f4cebd5aa4afb7c532661f215b16e0625f1aca2c83017fe5972

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 KB

Contents

module JSONAPI
  class IncludeDirectives
    # Construct an IncludeDirectives Hash from an array of dot separated include strings.
    # For example ['posts.comments.tags']
    # will transform into =>
    # {
    #   posts:{
    #     include:true,
    #     include_related:{
    #       comments:{
    #         include:true,
    #         include_related:{
    #           tags:{
    #             include:true
    #           }
    #         }
    #       }
    #     }
    #   }
    # }

    def initialize(resource_klass, includes_array)
      @resource_klass = resource_klass
      @include_directives_hash = { include_related: {} }
      includes_array.each do |include|
        parse_include(include)
      end
    end

    def include_directives
      @include_directives_hash
    end

    private

    def parse_include(include)
      path = JSONAPI::Path.new(resource_klass: @resource_klass,
                               path_string: include,
                               ensure_default_field: false,
                               parse_fields: false)

      current = @include_directives_hash

      path.segments.each do |segment|
        relationship_name = segment.relationship.name.to_sym

        current[:include_related][relationship_name] ||= { include: true, include_related: {} }
        current = current[:include_related][relationship_name]
      end

    rescue JSONAPI::Exceptions::InvalidRelationship => _e
      raise JSONAPI::Exceptions::InvalidInclude.new(@resource_klass, include)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jsonapi-resources-0.10.0.beta3 lib/jsonapi/include_directives.rb
jsonapi-resources-0.10.0.beta2.1 lib/jsonapi/include_directives.rb
jsonapi-resources-0.10.0.beta2 lib/jsonapi/include_directives.rb