Skip to content

Instantly share code, notes, and snippets.

@deevis
Last active August 28, 2017 17:29
Show Gist options
  • Save deevis/f798f8f4583214ccab18f17f584604f2 to your computer and use it in GitHub Desktop.
Save deevis/f798f8f4583214ccab18f17f584604f2 to your computer and use it in GitHub Desktop.
Ruby File.combine_relative_paths
# Note: there is also URI::join(base_path, relative_path) for URI paths
#
File.class_eval do
# combines "some/path/here" and "../there/something?asdf=qwerty" to be:
# "/some/path/there/something?asdf=qwerty"
#
# usage: File.combine_relative_path(base_path, relative_path)
#
def self.combine_relative_paths(base_path, relative_path)
base_path_parts = base_path.split("/")
relative_path_parts = relative_path.split("/")
doubledots_count = relative_path.scan(/\.\.\//).size
doubledots_count.times do
# remove base path parts from the back and relative parts from the front
base_path_parts.pop
relative_path_parts.shift
end
(base_path_parts + relative_path_parts).join("/")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment