Skip to content

Instantly share code, notes, and snippets.

@g33kidd
Created April 12, 2017 05:10
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 g33kidd/84a8c7402915c140b9e17f5336f3231d to your computer and use it in GitHub Desktop.
Save g33kidd/84a8c7402915c140b9e17f5336f3231d to your computer and use it in GitHub Desktop.
DOM Node Tree implementation in Crystal
module DOM
module NodeType
struct Text
property string
def initialize(@string : String)
end
end
struct Element
property tag_name, attributes
def initialize(@tag_name : String, @attributes : Hash(String, String))
end
end
end
class Node
@children : (Array(Node))?
@node_type : (NodeType::Text | NodeType::Element)?
def initialize(children, node_type)
@children = children
@node_type = node_type
end
def initialize
@children = nil
@node_type = nil
end
end
def text(data : String) : Node
Node.new children: [] of Node, node_type: NodeType::Text.new(data)
end
def element(name : String, attrs : Hash(String, String), children : Array(Node)) : Node
element_node = NodeType::Element.new tag_name: name, attributes: attrs
Node.new children: children, node_type: element_node
end
end
include DOM
dom = element("p", {"id" => "something", "href" => "else"}, [text("hello")] of Node)
p dom
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment