I want to create some small HTML snippets in Ruby. For example, in one place, I have an image URL and I want to create this from it
<img src='URL'>
Plus a few other similar things. But I haven’t found the right tool for it yet.
Alternatives I looked at and that didn’t work for me:
- Using an Erb file. This seems to be recommended in many places, but it seems overkill to me. This seems perfect if you want bigger snippets where you want to change the structure independently of thr code. I just want a few little snippet that can be generated directly in the code, adding the erb files adds too much indirection and complexity and isn’t justified for this. Of course I could live with it, but I don’t like it.
- Currently I just use string concatenation. This sucks and looks ugly. Of course, it works and given that it’s just a small internal project that only I run, I don’t have to worry about attack vectors. Besides, I could even fix escaping and make it moderately safe. But it’s just ugly as fuck, that’s why I would love to transition to a better solution.
- I found Nokogiri::HTML::Builder. When I saw it, I immediately loved the API and thought this is exactly what I want. However, it seems it wants to generate whole documents that also contain this “” stuff. I don’t want that, I need only snippets that contain my stuff without any extras. I tried figuring out how to surpress the doctype stuff, but I didn’t manage. I could of course postprocess the output and remove it, but then it gets brittle and just as ugly as any other solution, so I eventually gave up. But if someone knows how to make Nokogiri::HTML work for snippets rather than documents, that would be a nice solution.
Note that I already asked this on Stackoverflow, but it was closed for being too opinion based.
https://stackoverflow.com/questions/60169418/create-html-snippet-in-ruby#comment106424182_60169418