Sha256: 0ad773598906e5c357de6c5b0b63728c56b2d7b0ad4f9b30e48b7396b4b46238

Contents?: true

Size: 1.6 KB

Versions: 18

Compression:

Stored size: 1.6 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(includes_array)
      @include_directives_hash = { include_related: {} }
      includes_array.each do |include|
        parse_include(include)
      end
    end

    def include_directives
      @include_directives_hash
    end

    def model_includes
      get_includes(@include_directives_hash)
    end

    private

    def get_related(current_path)
      current = @include_directives_hash
      current_path.split('.').each do |fragment|
        fragment = fragment.to_sym
        current[:include_related][fragment] ||= { include: false, include_related: {} }
        current = current[:include_related][fragment]
      end
      current
    end

    def get_includes(directive)
      directive[:include_related].map do |name, directive|
        sub = get_includes(directive)
        sub.any? ? { name => sub } : name
      end
    end

    def parse_include(include)
      parts = include.split('.')
      local_path = ''

      parts.each do |name|
        local_path += local_path.length > 0 ? ".#{name}" : name
        related = get_related(local_path)
        related[:include] = true
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
jsonapi-resources-0.7.1.beta2 lib/jsonapi/include_directives.rb
jsonapi-resources-0.7.1.beta1 lib/jsonapi/include_directives.rb
jsonapi-resources-0.7.0 lib/jsonapi/include_directives.rb
jsonapi-resources-0.6.2 lib/jsonapi/include_directives.rb
jsonapi-resources-0.6.1 lib/jsonapi/include_directives.rb
jsonapi-resources-0.6.0 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.9 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.8 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.7 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.6 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.5 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.4 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.3 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.2 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.1 lib/jsonapi/include_directives.rb
jsonapi-resources-0.5.0 lib/jsonapi/include_directives.rb
jsonapi-resources-0.4.4 lib/jsonapi/include_directives.rb
jsonapi-resources-0.4.3 lib/jsonapi/include_directives.rb