HTML_slice: Enable Ruby classes the ability to generate reusable pieces of HTML
github.com
github.com
For example, this:
html_slice :stuff do
h1 'hello world' # @html_slice[:default] << '<h1>hello world</h1>'
text # @html_slice[:default] << '<p>Lorem ipsum dolor sit amet</p>'
div do
_ '<b> some raw html </b>'
end
end
Could be written in a helper like this: safe_join([
tag.h1('Hello world'),
tag.p('Lorem ipsum dolor sit amet'),
tag.div(<<~RAW.html_safe)
<b>some raw html</b>
RAW
])If you have a server-side rendered Ruby application with complicated view logic I can 100% recommend this approach (either Tubby, HTML_slice or Phlex). It's a super powerful way of structuring logic. You can create standalone classes which represents concepts (e.g. I've created a "ResourceCalendar" which renders a calendar view showing which resources are available for a given day), add methods which act on these, and finally make them renderable. It's heavily composable. It's very similar to React components, but here you also have the power of defining separate methods instead of having everything be hooks (with weird limitations) at the top of the component.
I also wrote a longer article here describing the different types of components you can build using Tubby: https://github.com/judofyr/timeless/blob/master/posts/compos.... I think this would also apply to HTML_slice and Phlex.
I just never liked "rendering" html elements directly in a ruby method. Feels weird, man.
Either you do SSR and you have to understand HTML or you don't and you can just build a Typescript front-end that calls a ruby server that doesn't generate HTML.
Lets say you do SSR and don't want to understand the HTML, then you can separate the project in two parts and give one part to someone else, but I still don't see how mixing classes and HTML helps.
Functions or templates are enough for SSR, lets be honest this is just about doing OOP everywhere and it creates coupling which IMO is no good.
I did this as an experiment for my own web framework [2] but I decided to use Haml for templating instead.
[1] https://docs.ruby-lang.org/en/3.4/Fiber.html#method-c-5B-5D