mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
Optimize Pathname#relative? / absolute?
This commit is contained in:
parent
28e60b0045
commit
39312cf4d6
Notes:
git
2020-09-15 03:18:47 +09:00
2 changed files with 14 additions and 11 deletions
|
@ -35,6 +35,13 @@ class Pathname
|
||||||
SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
|
SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
|
||||||
end
|
end
|
||||||
|
|
||||||
|
if File.dirname('A:') == 'A:.' # DOSish drive letter
|
||||||
|
ABSOLUTE_PATH = /\A(?:[A-Za-z]:|#{SEPARATOR_PAT})/o
|
||||||
|
else
|
||||||
|
ABSOLUTE_PATH = /\A#{SEPARATOR_PAT}/o
|
||||||
|
end
|
||||||
|
private_constant :ABSOLUTE_PATH
|
||||||
|
|
||||||
# :startdoc:
|
# :startdoc:
|
||||||
|
|
||||||
# chop_basename(path) -> [pre-basename, basename] or nil
|
# chop_basename(path) -> [pre-basename, basename] or nil
|
||||||
|
@ -222,7 +229,7 @@ class Pathname
|
||||||
# p.absolute?
|
# p.absolute?
|
||||||
# #=> false
|
# #=> false
|
||||||
def absolute?
|
def absolute?
|
||||||
!relative?
|
ABSOLUTE_PATH.match? @path
|
||||||
end
|
end
|
||||||
|
|
||||||
# The opposite of Pathname#absolute?
|
# The opposite of Pathname#absolute?
|
||||||
|
@ -237,11 +244,7 @@ class Pathname
|
||||||
# p.relative?
|
# p.relative?
|
||||||
# #=> true
|
# #=> true
|
||||||
def relative?
|
def relative?
|
||||||
path = @path
|
!absolute?
|
||||||
while r = chop_basename(path)
|
|
||||||
path, = r
|
|
||||||
end
|
|
||||||
path == ''
|
|
||||||
end
|
end
|
||||||
|
|
||||||
#
|
#
|
||||||
|
|
|
@ -269,17 +269,17 @@ class TestPathname < Test::Unit::TestCase
|
||||||
Pathname.new(path).relative?
|
Pathname.new(path).relative?
|
||||||
end
|
end
|
||||||
|
|
||||||
|
defassert(:relative?, true, '')
|
||||||
defassert(:relative?, false, '/')
|
defassert(:relative?, false, '/')
|
||||||
defassert(:relative?, false, '/a')
|
defassert(:relative?, false, '/a')
|
||||||
defassert(:relative?, false, '/..')
|
defassert(:relative?, false, '/..')
|
||||||
defassert(:relative?, true, 'a')
|
defassert(:relative?, true, 'a')
|
||||||
defassert(:relative?, true, 'a/b')
|
defassert(:relative?, true, 'a/b')
|
||||||
|
|
||||||
if DOSISH_DRIVE_LETTER
|
defassert(:relative?, !DOSISH_DRIVE_LETTER, 'A:.')
|
||||||
defassert(:relative?, false, 'A:')
|
defassert(:relative?, !DOSISH_DRIVE_LETTER, 'A:')
|
||||||
defassert(:relative?, false, 'A:/')
|
defassert(:relative?, !DOSISH_DRIVE_LETTER, 'A:/')
|
||||||
defassert(:relative?, false, 'A:/a')
|
defassert(:relative?, !DOSISH_DRIVE_LETTER, 'A:/a')
|
||||||
end
|
|
||||||
|
|
||||||
if File.dirname('//') == '//'
|
if File.dirname('//') == '//'
|
||||||
defassert(:relative?, false, '//')
|
defassert(:relative?, false, '//')
|
||||||
|
|
Loading…
Add table
Reference in a new issue