A little #to_s can do wonder in DRY-ing up your views
Do you do this every day?
<h1>Show - Blog <%= @blog.name %></h1>
<dl>
<dt>Author:</dt>
<dd><%= @blog.author.full_name %></dd>
</dl>
<ul>
<% for comment in @blog.comments do %>
<li>Posted by <%= comment.created_by.full_name %>: <%= comment.description %></li>
<% end %>
</ul>
I am lazy. Having to spell out in my views what field to render for every object when it is that field 90% of the time in my application gives me too much typing. When I render a @comment, you bet I want its description field most of the time; similarly, when I render a @user, you bet I want his/her full_name.
Don't forget all these erb tags at the end of day only render #to_s anyways, so you can just define your default field there to get rid of some typing as well:
class Blog < ActiveRecord::Base
def to_s
name
end
end
class User < ActiveRecord::Base
def to_s
first_name + ' ' + last_name
end
end
class Comment < ActiveRecord::Base
def to_s
description
end
end
Now, let's see how our view looks, 90% of the time:
<h1>Show - Blog <%= @blog %></h1>
<dl>
<dt>Author:</dt>
<dd><%= @blog.author %></dd>
</dl>
<ul>
<% for comment in @blog.comments do %>
<li>Posted by <%= comment.created_by %>: <%= comment %></li>
<% end %>
</ul>
See, it's a lot DRY-er and less verbose.
You will also notice that by doing this I eliminated a need to use a possible Object#try(:method) case:
<dd><%= @blog.author.try(:full_name) %></dd>
is no longer necessary, because a nil @blog.author will automatically give an empty string on the view. The end result is we all get to be lazier every day :-)
2 comments:
That's exactly what I was looking for. Thanks Stephen!
Good stuff. Thanks!
Post a Comment