views:

32

answers:

2

In my messages_controller I have the following private method:

def find_message_or_404(slug)
  message = user.messages.find_by_slug(slug)
  if message.nil?
    raise Error404
  end
  message
end

I find it not elegant and not very Rubist. Is there a way to improve it?

+2  A: 

Personally I don't think there's anything wrong with what you have (coding style wise), but maybe you like this better:

def find_message_or_404(slug)
  user.messages.find_by_slug(slug) or raise Error404
end
sepp2k
+3  A: 

If all you want to do is shorten the code to be more Ruby-like, how about:

def find_message_or_404(slug)
  user.messages.find_by_slug(slug) || raise Error404
end

Non-nil find_by_slug will return the message, otherwise it branches to the raise statement.

Mark Rushakoff
I've tried this one, but it gave me a syntax error (that I still can't totally decipher).
J. Pablo Fernández