Sha256: 7213f41869237ccd1418c07b2004e13897046f889a47895e5ea4e0b260855b6c

Contents?: true

Size: 1.74 KB

Versions: 15

Compression:

Stored size: 1.74 KB

Contents

# frozen_string_literal: true

require "hanami/router/segment"

module Hanami
  class Router
    # Trie node
    #
    # @api private
    # @since 2.0.0
    class Node
      # @api private
      # @since 2.0.0
      attr_reader :to

      # @api private
      # @since 2.0.0
      def initialize
        @variable = nil
        @fixed = nil
        @to = nil
      end

      # @api private
      # @since 2.0.0
      def put(segment, constraints)
        if variable?(segment)
          @variable ||= {}
          @variable[segment_for(segment, constraints)] ||= self.class.new
        else
          @fixed ||= {}
          @fixed[segment] ||= self.class.new
        end
      end

      # @api private
      # @since 2.0.0
      #
      def get(segment) # rubocop:disable Metrics/PerceivedComplexity
        return unless @variable || @fixed

        found = nil
        captured = nil

        found = @fixed&.fetch(segment, nil)
        return [found, nil] if found

        @variable&.each do |matcher, node|
          break if found

          captured = matcher.match(segment)
          found = node if captured
        end

        [found, captured&.named_captures]
      end

      # @api private
      # @since 2.0.0
      def leaf?
        @to
      end

      # @api private
      # @since 2.0.0
      def leaf!(to)
        @to = to
      end

      private

      # @api private
      # @since 2.0.0
      def variable?(segment)
        Router::ROUTE_VARIABLE_MATCHER.match?(segment)
      end

      # @api private
      # @since 2.0.0
      def segment_for(segment, constraints)
        Segment.fabricate(segment, **constraints)
      end

      # @api private
      # @since 2.0.0
      def fixed?(matcher)
        matcher.names.empty?
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
hanami-router-2.2.0.rc1 lib/hanami/router/node.rb
hanami-router-2.2.0.beta2 lib/hanami/router/node.rb
hanami-router-2.2.0.beta1 lib/hanami/router/node.rb
hanami-router-2.1.0 lib/hanami/router/node.rb
hanami-router-2.1.0.rc3 lib/hanami/router/node.rb
hanami-router-2.1.0.rc2 lib/hanami/router/node.rb
hanami-router-2.1.0.rc1 lib/hanami/router/node.rb
hanami-router-2.1.0.beta1 lib/hanami/router/node.rb
hanami-router-2.0.2 lib/hanami/router/node.rb
hanami-router-2.0.1 lib/hanami/router/node.rb
hanami-router-2.0.0 lib/hanami/router/node.rb
hanami-router-2.0.0.rc1 lib/hanami/router/node.rb
hanami-router-2.0.0.beta4 lib/hanami/router/node.rb
hanami-router-2.0.0.beta2 lib/hanami/router/node.rb
hanami-router-2.0.0.beta1 lib/hanami/router/node.rb