Class: Nx::AutoLink

Inherits:
Object
  • Object
show all
Defined in:
lib/nx/version.rb,
lib/nx/auto-link.rb

Constant Summary collapse

VERSION =
"0.1.2"

Class Method Summary collapse

Class Method Details

.start(html, tags) ⇒ Object



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
# File 'lib/nx/auto-link.rb', line 5

def self.start(html, tags)
  parsed_data = Nokogiri::HTML.parse(html)
  paragraphs = parsed_data.css("p")

  # tags = [
  #   { name: "下载", url: "http://www.baidu.com/tag/2.html" },
  #   { name: "建议", url: "http://www.baidu.com/tag/1.html" },
  #   { name: "python", url: "http://www.baidu.com/tag/5.html" },
  # ]

  paragraphs.each do |item|
    processed_html = item.inner_html
    tags.reject { |tag| tag[:processed] }.each do |tag|
      tag_name = tag[:name]
      tag_url = tag[:url]
      if item.inner_html.include?(tag_name)
        tag[:processed] = true
        tag_str = "<a role=\"tag\" title=\"#{tag_name}\" href=\"#{tag_url}\">#{tag_name}</a>"
        unless processed_html.include?(tag_str)
          processed_html = processed_html.sub(tag_name, tag_str)
        end
      end
    end
    item.inner_html = processed_html
  end

  parsed_data.at_css("body").inner_html
end