-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlibhtmltable.rb
84 lines (72 loc) · 1.8 KB
/
libhtmltable.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def table_to_csv(table_string)
doc = Nokogiri::HTML(table_string)
doc.xpath('//tr').each do |row|
row.xpath('th | td').each do |cell|
print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
end
print "\n"
end
end
def table_to_tsv(table_string)
doc = Nokogiri::HTML(table_string)
doc.xpath('//tr').each do |row|
row.xpath('th | td').each do |cell|
print cell.text.gsub("\n", ' ').gsub('\t', '\\t').gsub(/(\s){2,}/m, '\1'), "\t"
end
print "\n"
end
end
def print_table(options, table_string)
if options[:tsv]
table_to_tsv(table_string)
elsif options[:csv]
table_to_csv(table_string)
elsif options[:markdown]
puts ReverseMarkdown.convert(table_string)
elsif options[:asciidoc]
puts ReverseAdoc.convert(table_string)
elsif options[:html]
puts table_string
else
table_to_tsv(table_string)
end
end
def single_table(tables, options, numstring)
num = numstring.to_i
if num > tables.length
abort(" Table number out of range")
end
if options[:interactive]
puts " Converting table #{numstring}..."
else
puts "==Table ##{numstring}=="
end
table_string = tables[num - 1].inner_html
print_table(options, table_string)
end
def multiple_tables(tables, options, numstring)
num_array = numstring.split(",")
num_array.each do |n|
if !n.match(/\d/) then next end
single_table(tables, options, n)
puts
end
exit
end
def all_tables(tables, options)
counter = 1
tables.each do |table|
table_string = table.inner_html
puts "==Table ##{counter.to_s}=="
print_table(options, table_string)
puts
counter += 1
end
exit
end
def escape_url(url)
if url.match(/%/)
url = CGI.unescape(url)
end
url.gsub(/(.)/) { |u| u.match(URI::UNSAFE) ? CGI.escape(u) : u }
end