Module: BerkeleyLibrary::Util::Paths

Extended by:
Paths
Includes:
StringIOs
Included in:
Paths
Defined in:
lib/berkeley_library/util/paths.rb

Overview

This module, modeled on the Go path package, provides utility routines for modifying paths separated by forward slashes, such as URL paths. For system-dependent file paths, use Pathname instead.

Instance Method Summary collapse

Methods included from StringIOs

#getbyte

Instance Method Details

#abs?(path) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/berkeley_library/util/paths.rb', line 58

def abs?(path)
  path.to_s.start_with?('/')
end

#clean(path) ⇒ String?

Returns the shortest path name equivalent to path by purely lexical processing by:

  1. replacing runs of multiple / with a single /
  2. eliminating all . (current directory) elements
  3. eliminating all <child>/.. in favor of directly referencing the parent directory
  4. replaing all /.. at the beginning of the path with a single leading /

The returned path ends in a slash only if it is the root /.

Parameters:

  • path (String, nil)

    the path to clean

Returns:

  • (String, nil)

    the cleaned path, or nil for a nil path.

See Also:



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/berkeley_library/util/paths.rb', line 32

def clean(path)
  return unless path
  return '.' if ['', '.'].include?(path)

  StringIO.new.tap do |out|
    out << '/' if path[0] == '/'
    dotdot = (r = out.size)
    r, dotdot = process_next(r, dotdot, path, out) while r < path.size
    out << '.' if out.pos == 0
  end.string
end

#ensure_abs(path) ⇒ Object



62
63
64
# File 'lib/berkeley_library/util/paths.rb', line 62

def ensure_abs(path)
  abs?(path) ? path : "/#{path}"
end

#join(*elements) ⇒ String

Joins any number of path elements into a single path, separating them with slashes, ignoring empty elements and passing the result to #clean.

Parameters:

  • elements (Array<String>)

    the elements to join

Returns:

  • (String)

    the joined path



50
51
52
53
54
55
56
# File 'lib/berkeley_library/util/paths.rb', line 50

def join(*elements)
  elements = elements.reject { |e| [nil, ''].include?(e) }
  joined_raw = elements.join('/')
  return '' if joined_raw == ''

  clean(joined_raw)
end