Created
November 13, 2020 06:31
-
-
Save dchacke/34571504415b17d25de2f95d3885b180 to your computer and use it in GitHub Desktop.
Turning an HTML string into hiccup in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is gross: use Clojure unless you absolutely have | |
# to use Ruby. | |
# Required dependency: Nokogiri | |
# Use at your own risk. | |
def generate_hiccup parsed_html | |
if parsed_html.is_a?(Nokogiri::HTML::DocumentFragment) | |
parsed_html.children.map { |child| generate_hiccup child } | |
elsif parsed_html.is_a?(Nokogiri::XML::Element) | |
[ | |
parsed_html.name, | |
parsed_html.attributes.values.inject({}) do |acc, curr| | |
acc[curr.name] = curr.value # ugh why does Ruby return the *assigned* value rather than the result of the assignment?? | |
acc | |
end, | |
*parsed_html.children.map { |child| generate_hiccup child }] | |
elsif parsed_html.is_a?(Nokogiri::XML::Text) | |
parsed_html.content | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment