Tuesday, October 30, 2012

New and Edit actions to render same template

When I started learning rails, the '_form.html.erb' partial wasn't generated automatically in the rails scaffold generator, but it was commonly used, and eventually turned into a standard. And it was very important in the DRY sense, a main goal in rails programming.
But to me this wasn't enough. It always bothered me that now, this left two view files, 'new.html.erb' and 'edit.html.erb', almost entirely bare.

#app/views/user/new.html.erb
<h2>New user</h2>

<%=  render 'form' %>


#app/views/user/edit.html.erb
<h2>Edit user</h2>

<%=  render 'form' %>

Recently I was working on a project that involved internationalization (i18n), so after using translations on the  headers, the view would look like this:

#app/views/user/new.html.erb
<h2><%= t 'users.new.title' %></h2>

<%=  render 'form' %>


#app/views/user/edit.html.erb
<h2><%= t 'users.edit.title' %></h2>

<%=  render 'form' %>


#config/locales/en.yaml
en:
  users:
    new:
      title: "New user"
    edit:
      title: "Edit user"

At this point I was really frustrated by how ridiculous it was to have almost identical code in these 2 files. So I said to myself "to hell with this!", and deleted both views.
Obviously that's not all I did. I renamed the '_form.html.erb' to 'form.html.erb' so that it was no longer considered a partial, I added the following 1st line to the end of my 'edit' and 'new' actions, and I added the following 2nd line to the top of my 'form.html.erb' file:

#new and edit actions render command:
  render 'form'

#h2 tag moved to 'form.html.erb':
  <h2><%= t "users.#{params[:action]}.title" %></h2>

I'm not entirely sure this would be considered a good practice, but having those 2 redundant files off the table feels sooo good :)
Also, I suppose this little trick doesn't seem worth it if you're not already using i18n, but if you too are annoyed by these kinds of things, you should give it a try.

No comments:

Post a Comment