I like ruby and I don’t really link ERB templates …
Why ?
Because when you write ruby:
1 - It’s hard to generate malformed HTML (or others output languages) because you use methods that generate the code for you.
With ERB: template.html**.erb**
<div class="key-value">
<span class="key"><%= key %></span>
<span class="value"><%= value %></span>
</div>
Here I can forget to close the
With pure ruby and ActionView methods:
<%=
content_tag(:div, class: "key-value"){
concat content_tag(:span, class: "key"){ key }
concat content_tag(:span, class: "value"){ value }
}
%>
Here I cannot do this mistake.
2 - Rubocop can check the code to make it more tidy. (https://github.com/rubocop-hq/rubocop)
Perhaps I am wrong but it seems that Rubocop does not support ERB.
3 - It is ruby so code coverage should work on it (code coverage does not work on Rails views but it is another big issue, for me).
4 - The code can be easily moved to helper or presenter (copy / past).
How ?
If you want to use it, by default, you have to name your views with suffix .ruby
Then, by adding an initializer like config/initializers/ruby_views.rb
ActionView::Template.register_template_handler(:rb, :source.to_proc)
You can name them with suffix .rb and Rubocop will automatically check them
Using this the code above can be write as : template.html**.rb**
content_tag(:div, class: "key-value"){
concat content_tag(:span, class: "key"){ key }
concat content_tag(:span, class: "value"){ value }
}
Questions
Why do we (Rails coders) write views as templates using ERB … ?
Is it a go idea to write views using pure ruby ?
Best regards,
David