Module: URI

Defined in:
lib/spidr/extensions/uri.rb

Class Method Summary collapse

Class Method Details

.expand_path(path) ⇒ String

Expands a URI decoded path, into a proper absolute path.

Examples:

URI.expand_path('./path')
# => "path"
URI.expand_path('test/../path')
# => "path"
URI.exand_path('/test/path/')
# => "/test/path/"
URI.expand_path('/test/../path')
# => "/path"

Parameters:

  • path (String)

    The path from a URI.

Returns:

  • (String)

    The expanded path.



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
62
63
64
65
# File 'lib/spidr/extensions/uri.rb', line 32

def self.expand_path(path)
  if path.start_with?('/')
    leading_slash, path = path[0,1], path[1..-1]
  else
    leading_slash = ''
  end

  if path.end_with?('/')
    trailing_slash, path = path[-1,1], path[0..-2]
  else
    trailing_slash = ''
  end

  scanner = StringScanner.new(path)
  stack   = []

  until scanner.eos?
    if (dir = scanner.scan(/^[^\/]+/))
      case dir
      when '..' then stack.pop
      when '.'  then false
      else           stack.push(dir)
      end
    else
      scanner.skip(/\/+/)
    end
  end

  unless stack.empty?
    "#{leading_slash}#{stack.join('/')}#{trailing_slash}"
  else
    String.new('/')
  end
end