Class: UrlBuilder::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/url_builder/builder.rb

Overview

A builder class to construct a url with path segments and query params

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, separator: "/", query_params: {}) ⇒ Builder

Returns a new instance of Builder.

Parameters:

  • base_url (String)

    the base url to use. Must include the protocol

  • separator (String) (defaults to: "/")
    • optional path segment separator to use, defaults to '/'
  • query_params (Hash) (defaults to: {})
    • optional query params to use


12
13
14
15
16
17
# File 'lib/url_builder/builder.rb', line 12

def initialize(base_url:, separator: "/", query_params: {})
  @base_url = base_url
  @separator = separator
  @query_params = query_params.with_indifferent_access
  @path_segments = []
end

Instance Method Details

#add_query_param(key: "", value: "") ⇒ void

This method returns an undefined value.

Add a query param to the url

Parameters:

  • key (String) (defaults to: "")

    the key of the query param

  • value (String) (defaults to: "")

    the value of the query param



30
31
32
# File 'lib/url_builder/builder.rb', line 30

def add_query_param(key: "", value: "")
  @query_params[key] = value
end

#add_segment(segment) ⇒ void

This method returns an undefined value.

Add a path segment to the url

Parameters:

  • segment (String)

    the path segment to add



22
23
24
# File 'lib/url_builder/builder.rb', line 22

def add_segment(segment)
  @path_segments << segment
end

#to_sString

Build the url to a string

Returns:

  • (String)

    the url



36
37
38
39
40
41
42
43
# File 'lib/url_builder/builder.rb', line 36

def to_s
  path = @path_segments.filter(&:present?).join(@separator)
  query_string = @query_params.filter { |k, v| k.present? && v.present? }.map { |k, v| "#{k}=#{v}" }.join("&")
  url = @base_url
  url += @separator + path if path.present?
  url += "?#{query_string}" if query_string.present?
  url
end