Class: Rufio::Bookmark

Inherits:
Object
  • Object
show all
Defined in:
lib/rufio/bookmark.rb

Constant Summary collapse

MAX_BOOKMARKS =
9

Instance Method Summary collapse

Constructor Details

#initialize(config_file = nil, storage: nil) ⇒ Bookmark

Returns a new instance of Bookmark.



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

def initialize(config_file = nil, storage: nil)
  @config_file = config_file || default_config_file
  @storage = storage || JsonBookmarkStorage.new(@config_file)
  @bookmarks = []
  ensure_config_directory
  load
end

Instance Method Details

#add(path, name) ⇒ Object



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

def add(path, name)
  trimmed_name = name.strip
  return false if trimmed_name.empty?
  return false if @bookmarks.length >= MAX_BOOKMARKS
  return false if exists_by_name?(trimmed_name)
  return false if exists_by_path?(path)
  return false unless Dir.exist?(path)

  @bookmarks << { path: File.expand_path(path), name: trimmed_name }
  save
  true
end

#find_by_number(number) ⇒ Object



63
64
65
66
67
68
# File 'lib/rufio/bookmark.rb', line 63

def find_by_number(number)
  return nil unless number.is_a?(Integer)
  return nil if number < 1 || number > @bookmarks.length

  sorted_bookmarks[number - 1]
end

#get_path(name) ⇒ Object



58
59
60
61
# File 'lib/rufio/bookmark.rb', line 58

def get_path(name)
  bookmark = @bookmarks.find { |b| b[:name] == name }
  bookmark&.[](:path)
end

#listObject



70
71
72
# File 'lib/rufio/bookmark.rb', line 70

def list
  sorted_bookmarks
end

#loadObject



78
79
80
81
# File 'lib/rufio/bookmark.rb', line 78

def load
  @bookmarks = @storage.load
  true
end

#remove(name) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rufio/bookmark.rb', line 32

def remove(name)
  initial_length = @bookmarks.length
  @bookmarks.reject! { |bookmark| bookmark[:name] == name }

  if @bookmarks.length < initial_length
    save
    true
  else
    false
  end
end

#rename(old_name, new_name) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rufio/bookmark.rb', line 44

def rename(old_name, new_name)
  trimmed_new_name = new_name.strip
  return false if trimmed_new_name.empty?
  return false if old_name == trimmed_new_name
  return false if exists_by_name?(trimmed_new_name)

  bookmark = @bookmarks.find { |b| b[:name] == old_name }
  return false unless bookmark

  bookmark[:name] = trimmed_new_name
  save
  true
end

#saveObject



74
75
76
# File 'lib/rufio/bookmark.rb', line 74

def save
  @storage.save(@bookmarks)
end