forked from freeCodeCamp/devdocs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathurl.rb
More file actions
111 lines (91 loc) · 2.38 KB
/
url.rb
File metadata and controls
111 lines (91 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require 'uri'
require 'pathname'
module Docs
class URL < URI::Generic
PARSER = URI::Parser.new
def initialize(*args)
if args.empty?
super(*Array.new(9))
elsif args.length == 1 && args.first.is_a?(Hash)
args.first.assert_valid_keys URI::Generic::COMPONENT
super(*args.first.values_at(*URI::Generic::COMPONENT))
else
super
end
end
def self.parse(url)
return url if url.kind_of? self
new(*PARSER.split(url), PARSER)
end
def self.join(*args)
PARSER.join(*args)
end
def join(*args)
self.class.join self, *args
end
def merge!(hash)
return super unless hash.is_a? Hash
hash.assert_valid_keys URI::Generic::COMPONENT
hash.each_pair do |key, value|
send "#{key}=", value
end
self
end
def merge(hash)
return super unless hash.is_a? Hash
dup.merge!(hash)
end
def origin
if scheme && host
origin = "#{scheme}://#{host}"
origin.downcase!
origin << ":#{port}" if port
origin
else
nil
end
end
def normalized_path
path == '' ? '/' : path
end
def subpath_to(url, options = nil)
url = self.class.parse(url)
return unless origin == url.origin
base = path
dest = url.path
if options && options[:ignore_case]
base = base.downcase
dest = dest.downcase
end
if base == dest
''
elsif dest.start_with? File.join(base, '')
url.path[(path.length)..-1]
end
end
def subpath_from(url, options = nil)
self.class.parse(url).subpath_to(self, options)
end
def contains?(url, options = nil)
!!subpath_to(url, options)
end
def relative_path_to(url)
url = self.class.parse(url)
return unless origin == url.origin
base_dir = Pathname.new(normalized_path)
base_dir = base_dir.parent unless path.end_with? '/'
dest = url.normalized_path
dest_dir = Pathname.new(dest)
if dest.end_with? '/'
dest_dir.relative_path_from(base_dir).to_s.tap do |result|
result << '/' if result != '.'
end
else
dest_dir.parent.relative_path_from(base_dir).join(dest.split('/').last).to_s
end
end
def relative_path_from(url)
self.class.parse(url).relative_path_to(self)
end
end
end