towel off with .present? - taking try() one step further

April 21st, 2008 @ 02:26 PM

Chris over at ozmm.org wrote this great little method he calls try().

I liked the idea. Reduce


@person ? @person.name : nil

to


@person.try :name 

Great. Factor out the conditional logic.

In my rails apps, and rails apps I've worked on, however, i see tons of this in controllers:


if params[:search] && !params[:search].empty?

and this in views:


if @user.name and !@user.name.empty?

I mean, yuk. So, you could use try() in these cases, but that doesn't deal with the whole empty? thang. What are we asking for in these conditional spaghetti code moments? Typcially, we don't care about the actual value, we want to know that something exists and it has a value worth using?

So, I've started using .present?

It works like this:

1
2
3
4
5
6
7
8
9
10
11
# check if an incoming param is useful
if param.present? :search

# heck, check two at a time (returns true if they are both useful)
if param.present? :search, :query

# check if our user has a name worth printing
if @user.present? :name

# check if that collection actually has anything useful in it
if present? @users

So that is the trick. Stop getting "busted" because your method isn't there. Stop wasting your finger time checking to see if it's got anything inside.

The code

Throw this boy into lib/goodies.rb (and make sure to require it) http://pastie.caboo.se/183911

The name

Yeah, present? kinda sucks. What would be better?

Post a comment