Class: Hlsv::RiReportParser

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

Overview


Parser

Defined Under Namespace

Classes: Block

Instance Method Summary collapse

Constructor Details

#initialize(html_path) ⇒ RiReportParser

Returns a new instance of RiReportParser.



34
35
36
37
38
# File 'lib/hlsv/html2word.rb', line 34

def initialize(html_path)
  html = File.read(html_path, encoding: 'UTF-8')
  @doc = Nokogiri::HTML(html)
  @html_path = html_path
end

Instance Method Details

#parseObject



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
# File 'lib/hlsv/html2word.rb', line 40

def parse
  blocks = []

  h1   = @doc.at_css('header h1')
  info = @doc.at_css('.info-box')

  downloaded_at = Time.now.strftime('Downloaded on %Y-%m-%d at %H:%M')

  # Structure: <div class="info-box"><div flex><p>date</p><button>📄 Word</button></div></div>
  # target <p> to ignore the button
  date_text = if info
    p_tag = info.at_css('p')
    p_tag ? p_tag.text.strip : begin
      info.css('button, a').each(&:remove)
      info.text.gsub(/[^\x00-\x7F]/, '').gsub(/\s+/, ' ').strip
    end
  else
    ''
  end

  blocks << Block.new(type: :cover,
                      content: { title:         h1&.text&.strip.to_s,
                                 date:          date_text,
                                 downloaded_at: downloaded_at },
                      meta: {})

  blocks << Block.new(type: :toc, content: nil, meta: {})

  main = @doc.at_css('main.container') || @doc.at_css('main')
  return blocks unless main

  main.children.each do |node|
    next if node.text? && node.text.strip.empty?
    next if node['class']&.include?('info-box')
    blocks.concat(parse_node(node))
  end

  blocks
end