File, relative path handling.

  • Thread starter Hugh Sasse Staff Elec Eng
  • Start date
H

Hugh Sasse Staff Elec Eng

Before I attempt to re-invent this wheel:
Has anyone come up with a method for converting an absolute
filesystem path into a relative path, given the path to relate to?
Pruning off the front is relatively easy, but handling '../'
correctly is likely to be error prone. Given that I need to cope
with Ruby 1.6 and 1.8 at the moment, and I will need to do something
graceful if the paths are on different Windows drives, well, I
suspect someone has run into this before me.

I need relative paths so I can move between data sets for testing
and between machines as well.

Thank you,
Hugh
 
S

Sean O'Dell

Hugh said:
Before I attempt to re-invent this wheel:
Has anyone come up with a method for converting an absolute
filesystem path into a relative path, given the path to relate to?
Pruning off the front is relatively easy, but handling '../'
correctly is likely to be error prone. Given that I need to cope
with Ruby 1.6 and 1.8 at the moment, and I will need to do something
graceful if the paths are on different Windows drives, well, I
suspect someone has run into this before me.

I need relative paths so I can move between data sets for testing
and between machines as well.

Strange you should ask. I just wrote one of these and was about to port
it, and some other string utilities, to a C extension object.

It's brutal, but it works. Feel free to Rubify, anyone:

class String
public
def relative_path(topath)
frompath = self.clone
topath = topath.clone

fromdir = frompath.slice(/^.*?\//)
while(fromdir and frompath.slice(/^.*?\//) == topath.slice(/^.*?\//))
topath.slice!(/^.*?\//)
fromdir = frompath.slice!(/^.*?\//)
end

fromdir = frompath.slice!(/^.*?\//)
while(fromdir)
topath = "../" + topath
fromdir = frompath.slice!(/^.*?\//)
end

return topath
end

def relative_path!(topath)
self.replace(relative_path(topath))
end
end


Sean O'Dell
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,125
Messages
2,570,748
Members
47,301
Latest member
SusannaCgx

Latest Threads

Top