Skip to content

Instantly share code, notes, and snippets.

@dchacke
Created November 13, 2020 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dchacke/34571504415b17d25de2f95d3885b180 to your computer and use it in GitHub Desktop.
Save dchacke/34571504415b17d25de2f95d3885b180 to your computer and use it in GitHub Desktop.
Turning an HTML string into hiccup in Ruby
# 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