From a3b86375c946299c9216412e10c5bcf5234c7fcd Mon Sep 17 00:00:00 2001 From: Marcin Chrzanowski Date: Fri, 28 Jun 2019 19:12:42 +0200 Subject: Initial commit --- lib/pather.rb | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 lib/pather.rb (limited to 'lib/pather.rb') diff --git a/lib/pather.rb b/lib/pather.rb new file mode 100644 index 0000000..5ce7d02 --- /dev/null +++ b/lib/pather.rb @@ -0,0 +1,38 @@ +class Pather + def initialize + @assets = {} + @current_path = [] + end + + def add asset_id, path + @assets[asset_id] = @current_path + path.split('/') + end + + def path_to asset_id + other_path = @assets[asset_id] + find_path_between @current_path, other_path + end + + def find_path_between from, to + from, to = drop_common_prefix from, to + path = ('../' * from.length) + to.join('/') + end + + def drop_common_prefix path1, path2 + common_prefix_length = path1.zip(path2).take_while do |(segment1, segment2)| + segment1 == segment2 + end.length + + return path1[common_prefix_length..], path2[common_prefix_length..] + end + + def cd path + path.split('/').each do |segment| + if segment == '..' + @current_path.pop + else + @current_path.push segment + end + end + end +end -- cgit v1.2.3