Ruby has blocks, which enable all sorts of interesting idioms. I'm going to show one that will be familiar to Rails enthusiasts, but was new to me. I was reading some code in a book, and it had the following: def if_found(obj) if obj yield else render :text => "Not found.", :status => "404 Not Found" false end end Here's how you call it: if_found(obj) do # We have a valid obj. Render something with it. end The 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. I've been in the same situation in Python (using Pylons), and I coded something like: def handle_not_found(obj): if not obj: return render_404_page() return None Here's how you call it: response = handle_not_found(obj) if response: return response # Otherwise, continue normally. Pylons likes to return responses, whereas render in Ruby works as a side effect
This is a purely technical blog concerning topics such as Python, Ruby, Scala, Go, JavaScript, Linux, open source software, the Web, and lesser-known programming languages.
Ad maiorem Dei gloriam inque hominum salutem.