[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    FileTest.relative?
From:       Intransition <transfire () gmail ! com>
Date:       2010-12-21 23:35:19
Message-ID: abfa239e-0716-45dd-b696-9b143904e966 () s4g2000yql ! googlegroups ! com
[Download RAW message or body]

It seems FileTest lacks a `relative?` method (and conversely `absolute?
`). I need such a method. I went to write one but found my self not
100% certain about it being cross-platform. I wrote:

  module FileTest
    module_function

    def relative?(path)
      /\A[\/\\]/ !~ File.expand_path(path)
    end
  end

To put it in English, I expand the path and then simply check for a
leading '/' or '\'.

I noticed Pathname has a `relative?` method and I looked at it. It's
seems a bit bulky:

    if File::ALT_SEPARATOR
      SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}
#{Regexp.quote File::SEPARATOR}"
      SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/
    else
      SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}"
      SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/
    end

    def relative?
      path = @path
      while r = chop_basename(path)
        path, basename = r
      end
      path == ''
    end

    def chop_basename(path)
      base = File.basename(path)
      if /\A#{SEPARATOR_PAT}?\z/o =~ base
        return nil
      else
        return path[0, path.rindex(base)], base
      end
    end
    private :chop_basename

Is all that really necessary? My version may be too simplistic, but
surely there is more concise way to do this?

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic