Wednesday, February 18, 2009

RoR scaffolding breaks DRY principle

Nothing special, but I just realized that Ruby on Rails scaffolding breaks one of RoR's main principles - "Don't Repeat Yourself" (or DRY). When creating new and edit views for a new model, the exact same form is shown in both views:

>script/generate scaffold articles title:string body:text
...
create app/views/articles/index.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/edit.html.erb
create app/views/layouts/articles.html.erb
...

If we look at new.html.erb we see

<% form_for(@articles) do |f| %>
<p>
<b>Title</b><br />
<%= f.text_field :title %>
</p>

<p>
<b>Body</b><br />
<%= f.text_area :body %>
</p>

<p>
<%= f.submit "Create" %>
</p>
<% end %>

And looking at edit.html.erb we see

<% form_for(@articles) do |f| %>
<p>
<b>Title</b><br />
<%= f.text_field :title %>
</p>

<p>
<b>Body</b><br />
<%= f.text_area :body %>
</p>

<p>
<%= f.submit "Update" %>
</p>
<% end %>

Looks like we are repeating ourselves here. If an object has many properties the amount of repeated code increases greatly.


The solution to this is using a partial for the fields and I think scaffold generator should be smart enough to do something like this:

>script/generate scaffold articles title:string body:text
...
create app/views/articles/_form_fields.html.erb
create app/views/articles/index.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/edit.html.erb
create app/views/layouts/articles.html.erb
...

Making new.html.erb look like

<% form_for(@articles) do |f| %>
<% render :partial => 'form_fields', :locals => { :f => f } %>

<p>
<%= f.submit "Create" %>
</p>
<% end %>

0 comments:

Post a Comment