Method: Wgit::Url#relative?

Defined in:
lib/wgit/url.rb

#relative?(opts = {}) ⇒ Boolean Also known as: is_relative?

Returns true if self is a relative Url; false if absolute.

An absolute URL must have a scheme prefix e.g. 'http://', otherwise the URL is regarded as being relative (regardless of whether it's valid or not). The only exception is if an opts arg is provided and self is a page belonging to that arg type e.g. host; then the link is relative.

Examples:

url = Wgit::Url.new('http://example.com/about')

url.relative? # => false
url.relative?(host: 'http://example.com') # => true

Parameters:

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

    The options with which to check relativity. Only one opts param should be provided. The provided opts param Url must be absolute and be prefixed with a scheme. Consider using the output of Wgit::Url#to_origin which should work (unless it's nil).

Options Hash (opts):

Returns:

  • (Boolean)

    True if relative, false if absolute.

Raises:

  • (StandardError)

    If self is invalid (e.g. empty) or an invalid opts param has been provided.



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/wgit/url.rb', line 227

def relative?(opts = {})
  defaults = { origin: nil, host: nil, domain: nil, brand: nil }
  opts = defaults.merge(opts)
  raise "Url (self) cannot be empty" if empty?

  return false if scheme_relative?
  return true  if @uri.relative?

  # Self is absolute but may be relative to the opts param e.g. host.
  opts.select! { |_k, v| v }
  raise "Provide only one of: #{defaults.keys}" if opts.length > 1

  return false if opts.empty?

  type, url = opts.first
  url = Wgit::Url.new(url)
  if url.invalid?
    raise "Invalid opts param value, it must be absolute, containing a \
protocol scheme and domain (e.g. http://example.com): #{url}"
  end

  case type
  when :origin # http://www.google.com:81
    to_origin == url.to_origin
  when :host   # www.google.com
    to_host   == url.to_host
  when :domain # google.com
    to_domain == url.to_domain
  when :brand  # google
    to_brand  == url.to_brand
  else
    raise "Unknown opts param: :#{type}, use one of: #{defaults.keys}"
  end
end