Class: APIClientBuilder::URLGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/api_client_builder/url_generator.rb

Instance Method Summary collapse

Constructor Details

#initialize(domain) ⇒ URLGenerator

Receives a domain and parses it into a URI

Parameters:

  • domain (String)

    the domain of the API



7
8
9
10
11
# File 'lib/api_client_builder/url_generator.rb', line 7

def initialize(domain)
  @base_uri = URI.parse(domain)
  @base_uri = URI.parse('https://' + domain) if @base_uri.scheme.nil?
  @base_uri.path << '/' unless @base_uri.path.end_with?('/')
end

Instance Method Details

#build_route(route, **params) ⇒ URI

Defines a full API route and interpolates parameters into the route provided that the parameter sent in has a key that matches the parameter that is defined by the route.

Parameters:

  • route (String)

    defines the route endpoint

  • params (Hash)

    the optional params to be interpolated into the route

Returns:

  • (URI)

    the fully built route

Raises:

  • (ArgumentError)

    if route defined param is not provided



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/api_client_builder/url_generator.rb', line 23

def build_route(route, **params)
  string_params = route.split(%r{[\/=]}).select { |param| param.start_with?(':') }
  symboled_params = string_params.map { |param| param.tr(':', '').to_sym }

  new_route = route.clone
  symboled_params.each do |param|
    value = params[param]
    raise ArgumentError, "Param :#{param} is required" unless value
    new_route.gsub!(":#{param}", encode_ascii(value.to_s))
  end

  @base_uri.merge(new_route)
end