Rubyize this : 2nd edition

by Frank

Woooah… my first post in 3 weeks. Don’t worry, it will get back to the normal soon. I have a new job and, well, you know what it is… the stress and all the new stuff to learn. Anyway, my contract will expire by the end of August so things will run smoothly again pretty soon.

Yay! Another edition of Rubyize this. For those who don’t know what it is, you just have to rewrite the code snippet into some solid and idiomatic Ruby. This is a scientific process that is also called “Rewriting a code snippet into some solid and idiomatic Ruby”.

This week we dive a bit more into the Rails world. Take for grant that the following code is located inside a view :

<%songs = Song.find(:all)
for each song in songs%>

<%=song.title[0..0].upcase + song.title[1..song.title.length]%>

<% rating = song.rating if rating.nil? rating = 0 end if rating > 0 for i in 1..rating%> star <% end else%> This song hasn't been rated yet <%end end%>

Yikes… how ugly.

You can also specify some of your changes in plain english if you want (e.g. I would put this in a controller, I would use a partial to…, etc)

IMPORTANT NOTE : Since you cannot indent your code in the comments, you can try to put some dots or underscores instead of spaces… that way your code should remain fairly easy to read. Also, DON’T use <% and %> because it will get stripped out by wordpress! Use something else… like just the percentage sign “%”. I’m sorry about all these quirks… I absolutely have to make the comments “Ruby friendly”. For now, I strongly suggest that you copy your snippet in your clipboard BEFORE sending it. That way, if some of your code get stripped out, you won’t be that pissed off and you probably won’t try to kill me. That’s a win-win situation.

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon