Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created June 6, 2018 00:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/47c28849df7ab8faed348f77433cf0ad to your computer and use it in GitHub Desktop.
Save havenwood/47c28849df7ab8faed348f77433cf0ad to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require 'open-uri'
require 'ox'
class FoxHandler < Ox::Sax
def initialize
@h_tags = []
@h = nil
end
def start_element name
return unless name.match? /\Ah\d+\z/i
@h = name[1..-1].to_i
if @h_tags.last.to_i < @h
@h_tags << @h
elsif @h_tags.last > @h
@h_tags.pop
end
print ' ' * @h_tags.size.pred
print "[#{name}] "
end
def end_element _
@h = nil
end
def text value
return unless @h
puts value
end
end
html = URI.parse('https://jquery.com').read
def header_hierarchy html
Ox.sax_parse FoxHandler.new, html
end
header_hierarchy html
#[h2] jQuery
# [h3] Lightweight Footprint
# [h3] CSS3 Compliant
# [h3] Cross-Browser
#[h2] What is jQuery?
#[h2] Other Related Projects
# [h3] Resources
#[h2] A Brief Look
# [h3] DOM Traversal and Manipulation
# [h3] Event Handling
# [h3] Ajax
# [h3] Books
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment