January 20, 2007

Posted by John

Older: Finding Help Fast

Newer: I Don't Feel Like It, Why Don't You

A Handy Use Of to_s

Every app I work on has a user model. It’s responsible for authenticating people and hooking up the various action items in the system to who performed the action. Take for example these simple models:

class Post < ActiveRecord::Base
	belongs_to :user
end

class User < ActiveRecord::Base
	has_many :posts
end

You might have something like the following in posts/show.rhtml:

<div class="post">
	<h1><%=h @post.title %></h1>
	
	<h2>
		Posted by <%= @post.user.first_name %> 
		<%= @post.user.last_name %>
	</h2>
	
	<!-- etc, etc, etc, -->
</div>

The interesting thing is that all the erb (<%= %>) tags do is call to_s on the object inside. Knowing this, you could add the following to your user model:

class User < ActiveRecord::Base
	has_many :posts
	
	def to_s
		"#{first_name} #{last_name}"
	end
end

This allows simplifying your posts/show.rhtml view like so:

<div class="post">
	<h1><%=h @post.title %></h1>
	
	<h2>Posted by <%= @post.user %></h2>
	
	<!-- etc, etc, etc, -->
</div>

With the new to_s method, <%= @post.user %> is the same as calling <%= @post.user.first_name %> <%= @post.user.last_name %>.

Be creative. If you find yourself displaying the same things over and over for an instance of a object, just add to_s and you can save yourself some typing.

If you are interested in even more pimping of to_s, check out ActiveSupport::CoreExtensions::Time::Conversions to_formatted_s method and how they alias to_formatted_s with to_s to allow the handy time formatting of active record objects (ie: <%= user.created_at.to_s(:db) %>).

2 Comments

  1. Personally, I’d be more in favor of a custom helper to output this or a .name method. It’s obvious enough to other developers what is going to happen when this is rendered.

    IMHO, &lt;%= @post.user.name %&gt; seems like a good compromise for the sake of readability.

  2. Yeah, I probably didn’t pick the best example, but I still think this is a handy tip.

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.