Class: RandomWords::HTML2Markdown
- Inherits:
-
Object
- Object
- RandomWords::HTML2Markdown
- Defined in:
- lib/random-words/html2markdown.rb
Overview
Convert HTML to Markdown
Instance Attribute Summary collapse
-
#markdown ⇒ Object
readonly
Returns the value of attribute markdown.
Instance Method Summary collapse
-
#add_footnote(counter, link) ⇒ Object
Add a footnote to the list of links.
-
#add_link(link) ⇒ Object
Add a link to the list of links.
-
#initialize(str, baseurl = nil, meta = {}) ⇒ HTML2Markdown
constructor
Initialize the HTML2Markdown converter.
-
#output_for(node) ⇒ String
Convert a node to Markdown.
-
#output_for_children(node) ⇒ Object
Recursively convert child nodes.
-
#to_s ⇒ String
Convert the HTML to Markdown.
-
#wrap(str) ⇒ String
Wrap a string to 74 characters.
Constructor Details
#initialize(str, baseurl = nil, meta = {}) ⇒ HTML2Markdown
Initialize the HTML2Markdown converter
15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/random-words/html2markdown.rb', line 15 def initialize(str, baseurl = nil, = {}) @links = [] @footnotes = [] @baseuri = (baseurl ? URI.parse(baseurl) : nil) @section_level = 0 input = str.is_a?(String) ? str : str.output @encoding = input.encoding @markdown = output_for(Nokogiri::HTML(input, baseurl).root).gsub(/\n\n\n+/, "\n\n\n").strip @title = [:title] if [:title] @date = [:date] if [:date] @style = [:style] if [:style] = [:type] if [:type] end |
Instance Attribute Details
#markdown ⇒ Object (readonly)
Returns the value of attribute markdown.
10 11 12 |
# File 'lib/random-words/html2markdown.rb', line 10 def markdown @markdown end |
Instance Method Details
#add_footnote(counter, link) ⇒ Object
Add a footnote to the list of links
87 88 89 90 |
# File 'lib/random-words/html2markdown.rb', line 87 def add_footnote(counter, link) @footnotes << { counter: counter, title: link[:title] } @footnotes.length end |
#add_link(link) ⇒ Object
Add a link to the list of links
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/random-words/html2markdown.rb', line 94 def add_link(link) if @baseuri begin link[:href] = URI.parse(link[:href]) rescue Exception link[:href] = URI.parse('') end link[:href].scheme = @baseuri.scheme unless link[:href].scheme unless link[:href].opaque link[:href].host = @baseuri.host unless link[:href].host link[:href].path = @baseuri.path.to_s + '/' + link[:href].path.to_s if link[:href].path.to_s[0] != '/' end link[:href] = link[:href].to_s end @links.each_with_index do |l, i| return i + 1 if l[:href] == link[:href] end @links << link @links.length end |
#output_for(node) ⇒ String
Convert a node to Markdown
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/random-words/html2markdown.rb', line 137 def output_for(node) case node.name when 'title' @title = node.content '' when 'head' output_for_children(node) '' when 'style', 'script' '' when 'br' " \n" when 'p', 'div' "\n\n#{output_for_children(node)}\n\n" when 'section', 'article' @section_level += 1 o = "\n\n----\n\n#{output_for_children(node)}\n\n" @section_level -= 1 o when /h(\d+)/ "\n\n" + (('#' * (::Regexp.last_match(1).to_i + @section_level)) + ' ' + output_for_children(node)) + "\n\n" when /mark/ "==#{output_for_children(node)}==" when 'blockquote' @section_level += 1 o = "\n\n> #{output_for_children(node).lstrip.gsub("\n", "\n> ")}\n\n".gsub(/> \n(> \n)+/, "> \n").sub(/> \n$/, "\n") @section_level -= 1 o when 'cite' "*#{output_for_children(node)}*" when 'ul' "\n\n" + node.children.map { |el| next if el.name == 'text' "* #{output_for_children(el).gsub(/^(\t)|( )/, "\t\t").gsub(/^>/, "\t>")}\n" }.join + "\n\n" when 'ol' i = 0 "\n\n" + node.children.map { |el| next if el.name == 'text' i += 1 "#{i}. #{output_for_children(el).gsub(/^(\t)|( )/, "\t\t").gsub(/^>/, "\t>")}\n" }.join + "\n\n" when 'code' if @in_pre @in_pre = false node.text.strip else "`#{output_for_children(node).tr("\n", ' ')}`" end when 'pre' @in_pre = true lang = node['lang'] || node['language'] lang = '' if lang.nil? || lang.empty? "\n\n```#{lang}\n" + output_for_children(node).lstrip + "\n```\n\n" when 'hr' "\n\n* * * *\n\n" when 'a', 'link' link = { href: node['href'], title: node['title'] } if link[:href] =~ /^#fn:(\d+)/ counter = Regexp.last_match[1] add_footnote(counter, link) "[^fn#{counter}]" else "[#{output_for_children(node).tr("\n", ' ')}][#{add_link(link)}]" end when 'img' link = { href: node['src'], title: node['title'] } "![#{node['alt']}][#{add_link(link)}]" when 'video', 'audio', 'embed' link = { href: node['src'], title: node['title'] } "[#{output_for_children(node).tr("\n", ' ')}][#{add_link(link)}]" when 'object' link = { href: node['data'], title: node['title'] } "[#{output_for_children(node).tr("\n", ' ')}][#{add_link(link)}]" when 'i', 'em', 'u' "_#{output_for_children(node)}_" when 'b', 'strong' "**#{output_for_children(node)}**" when 'dl' "\n\n" + node.children.map do |el| case el.name when 'dt' "#{output_for_children(el)}\n" when 'dd' ": #{output_for_children(el)}\n\n" end end.join + "\n\n" # Tables are not part of Markdown, so we output WikiCreole when 'table' @table_header = true node.children.select do |c| %w[tr tbody thead].include?(c.name) end.map do |c| output_for(c) end.join when 'tr' header = "\n" if @table_header @table_header = false cells = node.children.count do |c| %w[th td].include?(c.name) end header = "\n|#{Array.new(cells) { '-------' }.join('|')}|\n" end node.children.select do |c| %w[th td].include?(c.name) end.map do |c| output_for(c) end.join.gsub('||', '|') + header when 'th', 'td' "| #{output_for_children(node)} |" when 'text' # Sometimes Nokogiri lies. Force the encoding back to what we know it is if /\S/.match?((c = node.content.force_encoding(@encoding))) c.gsub!(/\n\n+/, '<$PreserveDouble$>') c.gsub!(/\s+/, ' ') c.gsub('<$PreserveDouble$>', "\n\n") else c end else output_for_children(node) end end |
#output_for_children(node) ⇒ Object
Recursively convert child nodes
78 79 80 81 82 |
# File 'lib/random-words/html2markdown.rb', line 78 def output_for_children(node) node.children.map do |el| output_for(el) end.join end |
#to_s ⇒ String
Convert the HTML to Markdown
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 |
# File 'lib/random-words/html2markdown.rb', line 34 def to_s = '' if = " title: \#{@title}\n date: \#{@date}\n css: \#{@style}\n EOMETA\n case @meta_type\n when :multimarkdown\n meta = <<~EOMMD\n \#{meta.strip}\n\n EOMMD\n when :yaml\n meta = <<~EOYAML\n ---\n \#{meta.strip}\n ---\n EOYAML\n end\n end\n i = 0\n @markdown = TableCleanup.new(@markdown).clean\n out = \"\#{meta}\#{@markdown}\"\n\n if @links.any?\n out += \"\\n\\n\" + @links.map do |link|\n i += 1\n \"[\#{i}]: \#{link[:href]}\" + (link[:title] ? %( \"\#{link[:title]}\") : '')\n end.join(\"\\n\")\n end\n\n if @footnotes.any?\n out += \"\\n\\n\" + @footnotes.map { |link|\n \"[^fn\#{link[:counter]}]: \#{link[:title]}\"\n }.join(\"\\n\\n\")\n end\n out\nend\n" |
#wrap(str) ⇒ String
Wrap a string to 74 characters
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/random-words/html2markdown.rb', line 118 def wrap(str) return str if str.include?("\n") out = [] line = [] str.split(/[ \t]+/).each do |word| line << word if line.join(' ').length >= 74 out << line.join(' ') line = [] end end out << (line.join(' ') + (/[ \t\n]/.match?(str[-1..-1]) ? str[-1..-1] : '')) out.join("\n") end |