Class: NbfTools::Parse

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Parse

Returns a new instance of Parse.



8
9
10
# File 'lib/nbf_tools/parse.rb', line 8

def initialize options = {}
  @options = options
end

Instance Method Details

#folder_text(item) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/nbf_tools/parse.rb', line 36

def folder_text item
  return item.text unless item["personal_toolbar_folder"] == "true"
  if @options[:personal_toolbar_folder_text].to_s.empty?
    @options[:personal_toolbar_folder_text] = item.text
  else
    @options[:personal_toolbar_folder_text]
  end
end

#parse(file) ⇒ Object



12
13
14
15
# File 'lib/nbf_tools/parse.rb', line 12

def parse file
  @document = Nokogiri::HTML(File.open(file))
  parse_node_children(@document.xpath("/html/body/dl").first, Pathname.new("/"))
end

#parse_node_children(node, path) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/nbf_tools/parse.rb', line 17

def parse_node_children(node, path)
  node.children.each_with_object([]) do |c, items|
    case c.node_name
    when "dt"
      items.push(*parse_node_children(c, path))
    when "a"
      bookmark = c.to_h.merge("text" => c.text, "type" => NbfTools::Type::LINK, "path" => path.to_s)
      items.push bookmark
    when "h3"
      text = folder_text(c)
      folder = c.to_h.merge("text" => text, "type" => NbfTools::Type::FOLDER, "path" => (path + text).to_s, "items" => [])
      items.push folder
    when "dl"
      folder = items.reverse.find { |e| e["type"] == "folder" }
      folder.nil? ? items.push(*parse_node_children(c), path) : folder["items"] = parse_node_children(c, path + folder["text"])
    end
  end
end