Ruby on Rails Tuesday, June 26, 2018

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 <div> and generate malformed HTML.

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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/37ed0eae-fe55-4937-b60a-dd901e7dfeaa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment