m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/lib/pather.rb
diff options
context:
space:
mode:
authorMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2019-06-28 19:12:42 +0200
committerMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2019-06-28 19:13:20 +0200
commita3b86375c946299c9216412e10c5bcf5234c7fcd (patch)
treeb1cceccafa1fad92561bfda729e2ab9b7b62f1fc /lib/pather.rb
Initial commit
Diffstat (limited to 'lib/pather.rb')
-rw-r--r--lib/pather.rb38
1 files changed, 38 insertions, 0 deletions
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