File: uri_manager.rb

package info (click to toggle)
ruby-factory-bot 6.5.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,492 kB
  • sloc: ruby: 9,242; makefile: 6; sh: 4
file content (63 lines) | stat: -rw-r--r-- 1,483 bytes parent folder | download
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module FactoryBot
  # @api private
  class UriManager
    attr_reader :endpoints, :paths, :uri_list

    delegate :size, :any?, :empty?, :each?, :include?, :first, to: :@uri_list
    delegate :build_uri, to: :class

    # Concatenate the parts, sripping leading/following slashes
    # and returning a Symbolized String or nil.
    #
    # Example:
    #   build_uri(:my_factory, :my_trait, :my_sequence)
    #   #=> :"myfactory/my_trait/my_sequence"
    #
    def self.build_uri(*parts)
      return nil if parts.empty?

      parts.join("/")
        .sub(/\A\/+/, "")
        .sub(/\/+\z/, "")
        .tr(" ", "_")
        .to_sym
    end

    # Configures the new UriManager
    #
    # Arguments:
    #   endpoints: (Array of Strings or Symbols)
    #     the objects endpoints.
    #
    #   paths: (Array of Strings or Symbols)
    #     the parent URIs to prepend to each endpoint
    #
    def initialize(*endpoints, paths: [])
      if endpoints.empty?
        fail ArgumentError, "wrong number of arguments (given 0, expected 1+)"
      end

      @uri_list = []
      @endpoints = endpoints.flatten
      @paths = Array(paths).flatten

      build_uri_list
    end

    def to_a
      @uri_list.dup
    end

    private

    def build_uri_list
      @endpoints.each do |endpoint|
        if @paths.any?
          @paths.each { |path| @uri_list << build_uri(path, endpoint) }
        else
          @uri_list << build_uri(endpoint)
        end
      end
    end
  end
end