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.3.1'

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



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/philiprehberger/uri_kit.rb', line 242

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



266
267
268
269
270
271
272
# File 'lib/philiprehberger/uri_kit.rb', line 266

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



231
232
233
# File 'lib/philiprehberger/uri_kit.rb', line 231

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