Class: PathTable

Inherits:
Object
  • Object
show all
Defined in:
lib/overpath/path_table.rb

Overview

Controller for paths

Constant Summary collapse

PATHTABLE_FAVORITE_KEY =
'PATHTABLE_FAVORITE_KEY'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ PathTable

Returns a new instance of PathTable.



5
6
7
8
9
# File 'lib/overpath/path_table.rb', line 5

def initialize(file_path)
  @file_path = file_path
  @table = {}
  @history_limit = 5
end

Instance Attribute Details

#favoriteObject

Returns the value of attribute favorite.



43
44
45
# File 'lib/overpath/path_table.rb', line 43

def favorite
  @favorite
end

#history_limitObject

Returns the value of attribute history_limit.



44
45
46
# File 'lib/overpath/path_table.rb', line 44

def history_limit
  @history_limit
end

#tableObject

Returns the value of attribute table.



42
43
44
# File 'lib/overpath/path_table.rb', line 42

def table
  @table
end

Instance Method Details

#loadObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/overpath/path_table.rb', line 31

def load
  if File.exist?(@file_path)
    table = JSON.parse(File.open(@file_path, 'r').gets)
    if table.is_a?(Hash)
      @table = table.reject { |key, _value| key == PATHTABLE_FAVORITE_KEY }
      @table.each_value { |value| value.chomp!('/') }
      @favorite = table[PATHTABLE_FAVORITE_KEY]
    end
  end
  @table
end

#saveObject



11
12
13
14
15
16
17
# File 'lib/overpath/path_table.rb', line 11

def save
  File.open(@file_path + '.new', 'w+') do |file|
    save_to_file(file)
  end
  File.rename(@file_path, @file_path + '.old') if File.exist?(@file_path)
  File.rename(@file_path + '.new', @file_path)
end

#save_to_file(file) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/overpath/path_table.rb', line 19

def save_to_file(file)
  favorite = { PATHTABLE_FAVORITE_KEY => @favorite }
  table = @favorite ? @table.merge(favorite) : @table
  file.puts JSON.generate(table)
  if File.exist?(@file_path)
    File.foreach(@file_path).with_index do |line, i|
      break if i > (@history_limit - 1)
      file.puts line
    end
  end
end