Module: UriMapper

Defined in:
lib/urimapper.rb,
lib/urimapper/version.rb

Constant Summary collapse

RE_WWW =
Regexp.new(/^www\./)
RE_SLASH =
Regexp.new(/(\/)+$/)
RE_WHITE =
Regexp.new(/\s+/)
VERSION =
"1.0.0".freeze

Class Method Summary collapse

Class Method Details

.calculate_hash(what) ⇒ Object



67
68
69
# File 'lib/urimapper.rb', line 67

def calculate_hash(what)
  Digest::SHA1.hexdigest(what)
end

.inspectObject



71
72
73
# File 'lib/urimapper.rb', line 71

def inspect
  "UriMapper #{UriMapper::VERSION}"
end

.parse(where) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/urimapper.rb', line 13

def parse(where)
  where.freeze
  if where.nil? || where.empty?
    raise_error where
  end
  unless where.include?('.'.freeze)
    raise_error where
  end
  fqdn = where
  if where.slice(0, 2) == '//'.freeze
    fqdn = "http:#{where}"
  elsif where.slice(0, 4) != 'http'.freeze
    fqdn = "http://#{where}"
  end
  uri  = nil
  fqdn = fqdn.strip
  begin
    uri = ::Addressable::URI.parse(fqdn).to_hash
  rescue Exception => e
    raise_error e.message
  end

  path         = uri[:path].sub(RE_SLASH, ''.freeze).strip
  path         = (path.empty?) ? '/'.freeze : path
  query        = uri[:query].to_s.strip
  fragment     = uri[:fragment].to_s.strip
  host         = uri[:host].strip
  domain       = host.gsub(RE_WWW, ''.freeze).gsub(RE_WHITE, ''.freeze).chomp('.'.freeze)
  ssl          = (uri[:scheme] == 'https'.freeze) ? true : false
  port         = uri[:port] || ((ssl) ? 443 : 80)
  logical_port = (ssl) ? ((port == 443) ? ''.freeze : ":#{port}") : ((port == 80) ? ''.freeze : ":#{port}")
  canon        = "#{domain}#{logical_port}#{path}"
  canon        += "?#{query}" unless query.empty?
  canon        += "##{fragment}" unless fragment.empty?
  www          = (host.slice(0, 4)=='www.'.freeze) ? true : false
  {
      domain:       domain,
      www:          www,
      ssl:          ssl,
      path:         path,
      port:         port,
      fragment:     fragment,
      logical_port: logical_port,
      query:        query,
      canonical:    canon,
      raw:          "#{www ? 'www.'.freeze : ''.freeze}#{domain}#{logical_port}",
      hash:         Digest::SHA1.hexdigest(canon)
  }
end

.raise_error(where) ⇒ Object

Raises:

  • (ArgumentError)


63
64
65
# File 'lib/urimapper.rb', line 63

def raise_error(where)
  raise ArgumentError, "Invalid URL passed to parser: '#{where}'", []
end