Method: Flatfish::Url.absolutify

Defined in:
lib/flatfish/url.rb

.absolutify(url, cd) ⇒ Object

take a URL, return an absolute URL



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
# File 'lib/flatfish/url.rb', line 26

def absolutify url, cd 
  url = url.to_s
  # deal w/ bad URLs, already absolute, etc
  begin
    u = URI.parse(url)
  rescue
    # GIGO, no need for alarm
    return url
  end

  return url if u.absolute? # http://example.com/about
  c = URI.parse(cd)
  return c.scheme + "://" + c.host + url if url.index('/') == 0 # /about
  return cd + url if url.match(/^[a-zA-Z]+/) # about*

  # only relative from here on in; ../about, ./about, ../../about
  u_dirs = u.path.split('/')
  c_dirs = c.path.split('/')

  # move up the directory until there are no more relative paths
  u.path.split('/').each do |x|
    break unless (x == '' || x == '..' || x == '.')
    u_dirs.shift
    c_dirs.pop unless x == '.'
  end
  return c.scheme + "://" + c.host + c_dirs.join('/') + '/' +  u_dirs.join('/')
end