m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/lib/pather.rb
diff options
context:
space:
mode:
authorMarcin Chrzanowski <m@m-chrzan.xyz>2021-09-12 14:17:19 +0200
committerMarcin Chrzanowski <m@m-chrzan.xyz>2021-09-12 14:17:19 +0200
commitf3039744d72454e7e3b8cb1032266bcc172ce488 (patch)
tree5a92a698056e2cbec6f0b121a9ce31596e4a4581 /lib/pather.rb
Initial commit
Diffstat (limited to 'lib/pather.rb')
-rw-r--r--lib/pather.rb39
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/pather.rb b/lib/pather.rb
new file mode 100644
index 0000000..1f59df0
--- /dev/null
+++ b/lib/pather.rb
@@ -0,0 +1,39 @@
+class Pather
+ attr_accessor :current_path
+ 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