Class: TableAnalysis::Main

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

Class Method Summary collapse

Class Method Details

.generator(html, selected_row, *selected_cols) ⇒ Object



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
# File 'lib/table_analysis.rb', line 6

def self.generator(html, selected_row, *selected_cols)
  selected_cols = selected_cols.flatten 
  doc = Nokogiri::HTML(html, nil, 'utf-8')
  # 多个table,仅处理第一个
  table = doc.xpath('//table')[0]
  return false if table.nil?
  header_content_tds = []
  body_content_tds = []
  body_tr_size = 0
  table.xpath('./tr').each_with_index do |tr, tr_index|
    if tr_index == selected_row.to_i - 1
      tr.xpath('./td').each do |td|
        header_name = td.content
        colspan = td.attribute('colspan')&.value
        header_content_tds << [header_name, colspan]
      end
    elsif tr_index >= selected_row.to_i
      body_tr_size += 1
      tr.xpath('./td').each_with_index do |td, td_index|
        rowspan = td.attribute('rowspan')&.value 
        colspan = td.attribute('colspan')&.value
        body_content_tds << [rowspan, colspan]
      end
    end
  end

  header_tds = header_content_tds.map do |header_content_td|
    TableAnalysis::HeaderTd.config(header_content_td[0], header_content_td[1])
  end

  header = TableAnalysis::Header.config(selected_cols, header_tds)
  table = TableAnalysis::Table.config(body_tr_size, header)

  body_tds = body_content_tds.map do |body_td|
    TableAnalysis::BodyTd.config(body_td[0], body_td[1])
  end

  content_maps = TableAnalysis::Core.new(header, table, body_tds).entrance

  header_map = [Array.new(header_tds.size){0}]

  table_maps = header_map + content_maps

  p table_maps
  table_maps
end