File: namespace.rb

package info (click to toggle)
ruby-grape 1.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,156 kB
  • sloc: ruby: 25,265; makefile: 7
file content (47 lines) | stat: -rw-r--r-- 1,469 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# frozen_string_literal: true

require 'grape/util/cache'

module Grape
  # A container for endpoints or other namespaces, which allows for both
  # logical grouping of endpoints as well as sharing common configuration.
  # May also be referred to as group, segment, or resource.
  class Namespace
    attr_reader :space, :options

    # @param space [String] the name of this namespace
    # @param options [Hash] options hash
    # @option options :requirements [Hash] param-regex pairs, all of which must
    #   be met by a request's params for all endpoints in this namespace, or
    #   validation will fail and return a 422.
    def initialize(space, **options)
      @space = space.to_s
      @options = options
    end

    # Retrieves the requirements from the options hash, if given.
    # @return [Hash]
    def requirements
      options[:requirements] || {}
    end

    # (see ::joined_space_path)
    def self.joined_space(settings)
      settings&.map(&:space)
    end

    # Join the namespaces from a list of settings to create a path prefix.
    # @param settings [Array] list of Grape::Util::InheritableSettings.
    def self.joined_space_path(settings)
      Grape::Router.normalize_path(JoinedSpaceCache[joined_space(settings)])
    end

    class JoinedSpaceCache < Grape::Util::Cache
      def initialize
        @cache = Hash.new do |h, joined_space|
          h[joined_space] = -joined_space.join('/')
        end
      end
    end
  end
end