I was reading some code in a book, and it had the following:
def if_found(obj)Here's how you call it:
if obj
yield
else
render :text => "Not found.", :status => "404 Not Found"
false
end
end
if_found(obj) doThe code in the block will only execute if the obj was found. If it wasn't found, the response will already have been taken care of.
# We have a valid obj. Render something with it.
end
I've been in the same situation in Python (using Pylons), and I coded something like:
def handle_not_found(obj):Here's how you call it:
if not obj:
return render_404_page()
return None
response = handle_not_found(obj)Pylons likes to return responses, whereas render in Ruby works as a side effect whose return value isn't important. However, that's not my point.
if response:
return response
# Otherwise, continue normally.
My point is that the Python code uses "if response:" whereas the Ruby code uses "if_found(obj) do". Python uses an explicit if statement, whereas Ruby hides the actual if statement in a block. Similarly, Rubyists tend to write "my_list.each do |i|..." (even though Ruby has a for statement), whereas Pythonistas use "for i in my_list".
Ok, now that I've totally made a mountain out of a molehill, please note that I'm not saying either is better than the other. I'm just saying it's interesting to note the difference.

