Tip: Ruby On Rails Returning
Posted by anthony crumley, Wed Dec 05 14:02:00 UTC 2007
The Rails returning method can clarify your code. Its basic purpose is to semantically group code that creates the return value for a method. We could discuss its K Combinator Lambda Calculus roots but we won’t go there. Heck, I don’t even remember what that crap is.
Returning accepts two parameters. The first parameter initializes the return value. The second parameter is a block that creates the return value.
Returning doesn’t usually save lines of code or help with performance but it does make things a little clearer. One thing it does well is separate setup code from code that actually creates the return value. Consider the following helper method that returns the full name of a user.
def full_name(user) user = current_user unless user name = user.first_name name << ' ' + user.middle_name unless user.middle_name.blank? name << ' ' + user.last_name name end
Now the same method using returning to clarify what is being returned.
def full_name(user)
user = current_user unless user
returning String.new do |name|
name << user.first_name
name << ' ' + user.middle_name unless user.middle_name.blank?
name << ' ' + user.last_name
end
end