Module: UniformResourceIdentifier::Parser

Defined in:
lib/uniform_resource_identifier/parser.rb

Constant Summary collapse

STRICT =
/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
LOOSE =
/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/

Class Method Summary collapse

Class Method Details

.parse(uri, mode = :loose) ⇒ Object

Simply returns a Hash containing the captures mode can either be :strict or :loose

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/uniform_resource_identifier/parser.rb', line 8

def self.parse(uri, mode=:loose)
  raise(ArgumentError, "mode must either be :loose or :strict") unless [:loose, :strict].include?(mode)
  
  regexp = mode == :loose ? LOOSE : STRICT
  match  = uri.match(regexp)
  keys   = [
    :protocol, :authority, :user_info, :username, :password, :host,
    :port, :relative, :path, :directory, :file, :query, :anchor
  ]
  
  keys.each.with_index.inject({}) do |memo, (key, index)|
    memo[key] = match.captures[index]
    memo
  end
end