XML building using lamdas

Feb 17, 2023


Building HTML Programmatically with Curried Lambdas

When you need to build XML or HTML programmatically, there’s no shortage of
libraries available, such as XmlBuilder, Nokogiri, or REXML. But have you
ever thought of building it yourself? Here, we’ll explore how to use curried
lambdas for this purpose.

A basic HTML element is typically represented as:

<tag attributes>children</tag>

We can convert this structure into a curried lambda in Ruby:

node = -> tag, attrs, children { "<#{tag} #{attrs}>#{children.join}</#{tag}>" }.curry

In this representation, the children are an array of nodes. For our current
approach, attributes are represented as strings.

The beauty of currying lambdas is evident as it allows us to “pre-initialize”
them. We can then bind these lambdas to variables as shown below:

div = node.("div", "")
table = node.("table", "")
thead = node.("thead", "")
tbody = node.("tbody", "")
tr = node.("tr", "")
th = node.("th", "")
td = node.("td", "")

Now, leveraging these foundational building blocks, constructing an HTML
structure, like a table, becomes a breeze:

table_content = [
    thead.([]),
    tbody.([
        tr.([
            th.(["Header 1"]),
            th.(["Header 2"])
        ]),
        tr.([
            td.(["Data 1"]),
            td.(["Data 2"])
        ])
    ])
]

table_html = table.("").(table_content)

Conclusion

Using curried lambdas in Ruby not only provides an elegant and precise way to
articulate functionality but also offers a remarkably concise approach to
creating Domain Specific Languages (DSLs). The ability of lambdas to undergo
partial application allows for flexibility across the codebase, paving the way
for efficient and streamlined DSL creation.