Sha256: 744250d3ba164d097a7a230055502a5566482d85b7cb0bef71beb9f4c7eec549

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

require "hanami/api/middleware/node"

module Hanami
  class API
    module Middleware
      # Trie to register scopes with custom Rack middleware
      #
      # @api private
      # @since 0.1.1
      class Trie
        # @api private
        # @since 0.1.1
        def initialize(app)
          @app = app
          @root = Node.new
        end

        # @api private
        # @since 0.1.1
        def freeze
          @root.freeze
          super
        end

        # @api private
        # @since 0.1.1
        def add(path, app)
          node = @root
          for_each_segment(path) do |segment|
            node = node.put(segment)
          end

          node.app!(app)
        end

        # @api private
        # @since 0.1.1
        def find(path)
          node = @root

          for_each_segment(path) do |segment|
            break unless node

            node = node.get(segment)
          end

          return node.app if node&.app?

          @root.app || @app
        end

        # @api private
        # @since 0.1.1
        def empty?
          @root.leaf?
        end

        private

        # @api private
        # @since 0.1.1
        def for_each_segment(path, &blk)
          _, *segments = path.split(/\//)
          segments.each(&blk)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
hanami-api-0.2.0 lib/hanami/api/middleware/trie.rb
hanami-api-0.1.2 lib/hanami/api/middleware/trie.rb
hanami-api-0.1.1 lib/hanami/api/middleware/trie.rb