Skip to content

Instantly share code, notes, and snippets.

@datapimp
Last active August 29, 2015 14:13
Show Gist options
  • Save datapimp/67decb5a22d5ef0bb298 to your computer and use it in GitHub Desktop.
Save datapimp/67decb5a22d5ef0bb298 to your computer and use it in GitHub Desktop.

Given markdown input like this:

# Section One
# Section Two
## Section Two Article One
## Section Two Article Two
# Section Three
## Section Three Article One

I get HTML like this

h1 section one
h1 section two
h2 section two article one
h2 section two article two
h1 section three
h2 section three article one

Given HTML like this, I wrap it in Nokogiri::HTML.fragment so that I have a walkable dom structure

elements = fragment.children

I want to walk these children, and turn them into a hierarchy of nested HTML containers, so the structure will end up looking like:

section id="section-one"
  h1 Section One
section id="section-two"
  h1 section Two
  article id="section-two-article-one"
    h2 Section Two Article One
  article id="section-two-article-two"
    h2 Section Two Article Two

What I need: A ruby method for walking the children, analyzing the current heading level, and modifying the HTML so that it has the nested structure above

section id="section-one"
h1 Section One
section id="section-two"
h1 section Two
article id="section-two-article-one"
h2 Section Two Article One
article id="section-two-article-two"
h2 Section Two Article Two
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment