Class: UrlBuilder::Builder
- Inherits:
-
Object
- Object
- UrlBuilder::Builder
- 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
-
#add_query_param(key: "", value: "") ⇒ void
Add a query param to the url.
-
#add_segment(segment) ⇒ void
Add a path segment to the url.
-
#initialize(base_url:, separator: "/", query_params: {}) ⇒ Builder
constructor
A new instance of Builder.
-
#to_s ⇒ String
Build the url to a string.
Constructor Details
#initialize(base_url:, separator: "/", query_params: {}) ⇒ Builder
Returns a new instance of Builder.
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
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
22 23 24 |
# File 'lib/url_builder/builder.rb', line 22 def add_segment(segment) @path_segments << segment end |
#to_s ⇒ String
Build the url to a string
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 |