Rails refactoring fun - looking at old code

Every so often I get to do some updates on code I wrote years ago. It's often a hideous experience (especially when you're in a rush and did not write the code), but it can be entertaining and enjoyable. Taking a big sloppy mess of redundancies and complications and making it readable, clean, and orderly—it's a satisfying experience refactoring old unrefined code—a nice guage of your growth as a human being in the small but large area of your life as a programmer.

I'll share just a few quick examples. The first two are from a Rails project I had originally built when I was getting my hands dirty with Ruby (and was still a bit handicapped by having programmed so long in PHP).

 

Example 1: ActiveRecord scopes

speakers = Page.find_all_by_page_type_id(PageType.find_by_name("speaker").id, :conditions=>{:status => 'online'}, :order=>"position")

To...

 speakers = Page.speakers

 

Example 2: Unnecessary for loops

<% if page.categories.count > 0
    c_count = 0
    page.categories.each do |c|
        c_count+=1
        if c_count >1 
            %>/  <%
        end %>
         <%=c.name %>
     <% end %>
<% end %>

To...

 <%= page.categories.map(&:name).join("/") ?>

Example 3: Ambiguous variable names -- This was code written by a previous developer. From what I could tell "in" and "out" had nothing to do with what the numbers actually were, nor anything to do with the words "in" and "out"... it caused me a lot of confusion.

EXACT_TARGET_LISTS = {
    :in       => '867530933',
    :out      => '9021055'
}

To...

EXACT_TARGET_LISTS = {
    :newsletter_welcome   => '867530933',
    :member_welcome      => '90210555'
}
blog comments powered by Disqus