Module: Philiprehberger::UriKit

Defined in:
lib/philiprehberger/uri_kit.rb,
lib/philiprehberger/uri_kit/version.rb

Defined Under Namespace

Classes: Error, Url

Constant Summary collapse

VERSION =
'0.4.0'

Class Method Summary collapse

Class Method Details

.build(host:, path: '/', params: {}, scheme: 'https') ⇒ Url

Build a URL from components

Parameters:

  • host (String)

    hostname

  • path (String) (defaults to: '/')

    URL path

  • params (Hash) (defaults to: {})

    query parameters

  • scheme (String) (defaults to: 'https')

    URL scheme

Returns:

  • (Url)

    built URL object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/philiprehberger/uri_kit.rb', line 256

def self.build(host:, path: '/', params: {}, scheme: 'https')
  query = if params.empty?
            nil
          else
            params.map do |k, v|
              "#{::URI.encode_www_form_component(k)}=#{::URI.encode_www_form_component(v)}"
            end.join('&')
          end

  uri = ::URI::Generic.build(
    scheme: scheme,
    host: host,
    path: path.start_with?('/') ? path : "/#{path}",
    query: query
  )

  Url.new(uri.to_s)
end

.join(base, relative) ⇒ Url

Join a base URL with a relative path

Parameters:

  • base (String)

    base URL

  • relative (String)

    relative path

Returns:

  • (Url)

    joined URL



280
281
282
283
284
285
286
# File 'lib/philiprehberger/uri_kit.rb', line 280

def self.join(base, relative)
  base_uri = ::URI.parse(base.to_s)
  joined = base_uri.merge(relative.to_s)
  Url.new(joined.to_s)
rescue ::URI::InvalidURIError => e
  raise Error, "Invalid URL: #{e.message}"
end

.parse(url) ⇒ Url

Parse a URL string

Parameters:

  • url (String)

    URL to parse

Returns:

  • (Url)

    parsed URL object



245
246
247
# File 'lib/philiprehberger/uri_kit.rb', line 245

def self.parse(url)
  Url.new(url)
end