-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.rb
44 lines (38 loc) · 1.16 KB
/
app.rb
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
39
40
41
42
43
44
require 'sinatra'
require 'open-uri'
require 'nokogiri'
get '/' do
erb :"layout.html"
end
post '/' do
url = params[:"site-url"][0..6] == "http://" ? params[:"site-url"] : "http://" + params[:"site-url"]
@message = ""
begin
@json_nodes = generate_json_nodes Nokogiri::HTML(open(url))
rescue
@message = "Invalid URL."
end
erb :"layout.html"
end
private
def node_id(node)
return "=>body---" if node.name == "body"
id = node_id(node.parent) + "=>" + node.name
id += "#" + node[:id] if node[:id]
id += "." + node[:class] if node[:class]
id + "---"
end
def generate_json_node(parent_node)
js = '{id:\"' + ($json_node_id+=1).to_s + '\", name:\"' + node_id(parent_node).split('---').last[2..-1] + '\", data:{}, children:['
parent_node.children.each do |child_node|
next unless !$json_node_ids.member?(node_id(child_node)) && (child_node[:id] or child_node[:class])
$json_node_ids << node_id(child_node)
js += generate_json_node(child_node) + ","
end
js + "]}"
end
def generate_json_nodes(page)
$json_node_id = 0
$json_node_ids = []
generate_json_node page.xpath('//body').first
end