jensljungblad / elemental_components

Simple view components for Rails 5.1+
MIT License
76 stars 5 forks source link

Strategies for rendering block content #32

Closed jensljungblad closed 4 years ago

jensljungblad commented 5 years ago

Currently the content of the block of a component or element is rendered using to_s, like this:

<div class="alert">
  <%= alert %>
</div>

<%= component "alert" do %>
  Hello
<% end %>

Upsides:

Downsides:

Alternative 1: Introduce named variable for the captured block

Something like block, or content.

Upsides:

Downsides:

Alternative 2: Leverage content_for

Rails has a content_for (and a content_for?) helper that perhaps could be leveraged:

<div class="alert">
  <%= content_for(alert) %>
</div>

<%= component "alert" do %>
  Hello
<% end %>
class Element
  def initialize
    …
    @view.content_for(self, &block)
  end
end

Upsides:

Downsides:

Alternative 3: Connect the block to an attribute

This is something I tried out but later discarded because it felt like I was over-engineering things, and muddied the concepts. Basically the user could choose an attribute name for the block to be captured to, and then you could either populate it like an attribute or by passing a block. Something like:

<div class="alert">
  <%= alert.message %>
</div>

<%= component "alert" do %>
  Hello
<% end %>
class AlertComponent < Components::Component
  attribute :message

  capture_block_to :message
end

Upsides:

Downsides

jensljungblad commented 4 years ago

Closed by https://github.com/jensljungblad/elemental_components/pull/42. Went with the first alternative.