m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/lib/pather.rb
blob: 5ce7d02baa13e3954dad6677f17b006ae07a8305 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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