Class: Bookmarks

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

Instance Method Summary collapse

Constructor Details

#initialize(search_term) ⇒ Bookmarks

try to read bookmarks



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/bookmarks.rb', line 31

def initialize(search_term)
  @conf = BConfig.new
  begin
    local_bookmarks = JSON.parse(open(@conf.bookmarks).read)
    @chrome_bookmarks = local_bookmarks['roots']['bookmark_bar']['children']
  rescue
    puts "Warning: ".yel +
      "Chrome JSON Bookmarks not found."
    puts "Suggest: ".grn +
      "web --install bookmarks"
    @chrome_bookmarks = {}
  end

  # clean search term, set urls
  @searching = /#{search_term}/i
  @allurls = []
  parse
end

Instance Method Details

#autocompleteObject

output for zsh



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/bookmarks.rb', line 52

def autocomplete
  @allurls.each do |url|
    # delete anything not allowed in linktitle
    name = url.folder + url.title.gsub(/[^a-z0-9\-\/_]/i, '')
    name.gsub!(/\-+/, '-')
    name.gsub!(/ /,'')
    name = name.window(TERMWIDTH)

    # remove strange things from any linkurls
    link = url.url.gsub(/[,'"&?].*/, '')
    link.gsub!(/.*:\/+/,'')
    link.gsub!(/ /,'')
    link = link[0..TERMWIDTH]

    # print out title and cleaned url, for autocompetion
    puts url.id + ":" + name + ":" + link
  end
end

#bookmark_url(id) ⇒ Object

get link (from id number)



72
73
74
75
76
77
78
# File 'lib/bookmarks.rb', line 72

def bookmark_url(id)
  @allurls.each do |url|
    if id == url.id
      return url.url
    end
  end
end

#parse(root = nil) ⇒ Object

recursively parse gc bookmarks



81
82
83
84
85
86
87
88
89
90
# File 'lib/bookmarks.rb', line 81

def parse(root=nil)
  # root - parent folder in ruby
  root = Folder.new @chrome_bookmarks if root.nil?

  # all current urls, to hash
  root.json.each {|x| parse_link root.title, x }

  # all next-level folders, to array
  root.json.each {|x| parse_folder root, x }
end

#parse_folder(base, link) ⇒ Object

discover and parse folders



103
104
105
106
107
108
109
# File 'lib/bookmarks.rb', line 103

def parse_folder(base, link)
  if link['type'] == 'folder'
    title = base.title + link['name'] + '/'
    subdir = Folder.new(title, link['children'])
    parse(subdir)
  end
end

add link to results



93
94
95
96
97
98
99
100
# File 'lib/bookmarks.rb', line 93

def parse_link(base, link)
  checking = [base, link['name'], link['url'], link['id']]
  if checking.any? {|x| @searching.match x }
    if link['type'] == 'url'
      @allurls.push(Bookmark.new base, link['name'], link['url'], link['id'])
    end
  end
end