Skip to content

Commit

Permalink
added chop_path
Browse files Browse the repository at this point in the history
  • Loading branch information
blindgaenger committed Nov 5, 2011
1 parent edfb7d5 commit ab4e27c
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/fs/alias.rb
Expand Up @@ -15,6 +15,7 @@ module Alias
:ln => :link,
:dir? => :directory?,
:expand => :expand_path,
:chop => :chop_path,
:[] => :join,
}

Expand Down
14 changes: 14 additions & 0 deletions lib/fs/base.rb
Expand Up @@ -173,6 +173,20 @@ def expand_path(path, base=nil)
File.expand_path(path, base)
end

# chop base from the path
# if it's not a subdir the absolute path will be returned
def chop_path(path, base='.')
full_base = File.expand_path(base)
full_path = File.expand_path(path)
if full_path == full_base
'.'
elsif full_path.start_with?(full_base)
full_path[full_base.size+1..-1]
else
full_path
end
end

# checks for a slash at the beginning
def absolute?(path)
%r{\A/} =~ path ? true : false
Expand Down
31 changes: 31 additions & 0 deletions spec/base_spec.rb
Expand Up @@ -440,6 +440,37 @@
end
end

describe '::chop_path' do
it 'does nothing for relative paths' do
FS.chop_path('.').should eql('.')
FS.chop_path('./foo').should eql('foo')
FS.chop_path('foo').should eql('foo')
FS.chop_path('foo/bar').should eql('foo/bar')
end

it 'does not chop for non subdirs' do
FS.chop_path('/').should eql('/')
FS.chop_path('..').should eql(File.expand_path('..'))
FS.chop_path('/foo', '/foo/bar').should eql('/foo')
end

it 'chop absolute the path' do
here = File.expand_path('.')
FS.chop_path(here).should eql('.')
FS.chop_path(File.join(here, '.')).should eql('.')
FS.chop_path(File.join(here, 'foo')).should eql('foo')
FS.chop_path(File.join(here, 'foo/bar')).should eql('foo/bar')
FS.chop_path('/foo/bar').should eql('/foo/bar')
end

it 'uses a base dir to chop the path' do
FS.chop_path('.', '.').should eql('.')
FS.chop_path('/', '/').should eql('.')
FS.chop_path('/foo', '/foo').should eql('.')
FS.chop_path('/foo/bar', '/foo').should eql('bar')
end
end

describe '::absolute?' do
it 'checks for an absolute path' do
FS.absolute?('/').should be_true
Expand Down

0 comments on commit ab4e27c

Please sign in to comment.