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