I have been working in ruby and in rails for a few months now. I came back to my Large Multinational Corporation recharged with a new zest for life. Flowers smell better. The sky is bluer. My children suddenly started behaving.
Maybe not all of those things, but I do enjoy my job again.
We recently took out a Basecamp subscription to manage the handful of projects that have become collaborative projects. This is also very exciting because we’re finally doing things that we’ve been talking about doing for years.
We’re making decisions together, and the office is more fun in general. At least this is the case on the technology side of the office. Dealing with the customers is still dealing with the customers - if you know what I mean.
Now on to the point of this entry…. So I have sort of taken the lead on one of the big collaborative projects. We needed to expand on some functionality in one of the controllers, so I took a run at refactoring it. No big deal. I wrote tests as I went, and it came together nicely.
I took another look at it a couple of days later because I needed to expand the functionality a little more.
I had some finder methods in the model. One of them was giving me some trouble in the controller. It was late afternoon and it was Friday. I wanted to wrap this thing up. So here is what I wrote:
def self.find_an_id_by_another_id(another_id)
if another_id.blank?
nil
else
search = find(:all, :select => ["field"], :conditions => "another_id=#{another_id}")
# not sure if this is a lame hack or not, but I just need an_id
search[0]["an_id"]
end
end
Seriously. I think if you write in the comment that you think it is a lame hack that you should just shut it down right there. Could that approach have been any more perl?
So here is how I rewrote it:
def self.find_by_user(user_id = nil)
if user_id.nil? or user_id.blank?
nil
else
User.find(:all, :conditions => "user_id=#{user_id}").first
end
end
Now the object that is returned is not an array, but the specific item that I wanted in the first place. I should add that there will only be 1 item found by the search criteria. Sure - there is probably still an even better way to do this. This looks better, and the tests all work. I’ve had some fun writing tests this week. Really.
I need to spend some time with tests for AJAX stuff. Maybe fodder for another post….