On Sat, Feb 28, 2009 at 10:02 AM, ericindc firstname.lastname@example.org
Makes sense for consistency’s sake. My initial concern is about
overriding a core method. What if I needed to_s elsewhere?
Usually, you shouldn’t need it unless what you need is a “string
representation of your object” (yes, i’m sounding like a broken vinyl
now ;D), and receiving a user_name or a title would probably be what
you’re looking for.
Also, if it’s something for debugging purposes in Ruby we use “inspect”.
Plus, wouldn’t I be writing more code given that every model must now have a
custom defined to_s method? Unless adding extra virtual attributes is
bad, would it be less work (given that I’d have to change two models
at this point) to just add a “title” method for those that doesn’t
respond to title?
Yes and no. When you say that it’s “title”, it has to be a method
called title, so you’re stuck with this “title” thing, if a model has
a title and you don’t want to use it, you’re about to have a problem.
Using to_s or a to_label (this one feels clumsy) means your view code
don’t need to know which method is going to be called, which
simplifies changes in the future. Imagine that today, when presenting
a user, you show it’s full name, but later on there’s a request to,
instead of showing the full name, show only the login, if you had a
full_name call at every user show, you’d have to change them all to
login, but if you had oveeriden the to_s method you would just have to
change it in one place.
Also, when you override the to_s method you don’t need to call it at
the view, as you need to call the “title” method:
<%= link_to user, user %>
The link_to helper will automatically call “to_s” at your object, so
you don’t have to call it by yourself.
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/