Sometimes I wonder why we can’t have a standard for something like server side rendered single file components/pages in rails. Here are some frontend inspirations:
Often I think why we always need to split html, css, js, i18n into that many files, and then having to reference each other. Rails already removes a lot of this reference pain, but not all of it.
I could imagine something like this, but of course a lot more refined:
# app/views/animals.sfc.erb
<div>
<%= @animals.each do |animal| %>
<% tag.h1 animal, class: "background-#{animal.id}", onclick: happy %>
<%= animal.name %> is a <%= t :beautiful %> animal
<% end %>
</div>
<script>
# Why do we need to place ALL code in app/javascript ? Let's place some local code here too
const happy = () => { alert("the animal is happy, go to <%= animals_path %> to find out more") }
# of course, we need to handle all the edge cases of loading this correctly. And yes, I want to inject all the rails magic directly into my javascript responses.
</script>
<style>
# inherit from standard asset pipeline and allow local-only overrides
<%= @animals.each do |animal| %>
.background-<%= animal.id%> {
background-color: <%= animal.color %>
font-size: <%= animal.size%>px;
}
<% end %>
</style>
<i18n>
# inherit from standard i18n and allow local overrides
de:
beautiful: "wunderschön"
</i18n>
What your opinion on single file components? I think it would increase the chance of code duplication while introducing an easy way to handle edge cases easier. An easy version could be implemented using content_for()
but I think that would be too limited.
Generally I would like to achieve more simplicity and not complexity, in this case by grouping all required code as much as possible.