Project

General

Profile

Actions

Feature #6201

closed

do_something then return :special_case (include "then" operator)

Added by rosenfeld (Rodrigo Rosenfeld Rosas) over 12 years ago. Updated over 12 years ago.

Status:
Rejected
Target version:
[ruby-core:43672]

Description

=begin
I've read several aproaches to deal with this case and this just feels like Ruby doesn't have a good idiom yet for the common use case.

You want to do some special action under certain conditions and then return the method.

I've once proposed some way to return from the callee:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/41681

But I agree with other that found that approach a dangerous one.

One of the common idioms I see is writing code like this:

render action: NOT_FOUND and return

The problem with this is that it won't work if render returns nil or false. And render return value isn't supposed to have any meaning.

So while reading some articles this issue got back to me, but this time I think I found a more elegant solution for improving the Ruby language in a way to better support this pretty common use case.

If you read the article below, you'll see the suggested code by its author, Avdi Grimm:

http://devblog.avdi.org/2012/03/23/unless-readable-else-confused/

return follow(response['location']) if response.redirect?

I also prefer this style, but I don't like this other common approach to the same problem: to include a meaningless return in the front of the special case statement.

What if you really want to return something else?

So, I'd like Ruby to support "then" besides "and" and "or" so that they will be used for what they were intended for:

save_file and return :saved # you only want to return :saved if save_file returned true

special case, it wasn't possible to save the file

notify_error_by_email or raise EmailNotWorking
handle_error

But for the example in the mentioned article, I'd prefer to write code like this:

follow response['location'] if response.redirect? then return :redirected

or

follow response['location'] then return :redirected if response.redirect?

I'm not sure about what precedence "then" should have.

It means: no matter the return value, I want this to be run after that method.

Another approach, since this would be used for earlier exit, would be to have something like then_return instead (a bit more constraint, but still useful):

render :redirected then_return if should_be_redirected?

Any of those approaches would enable better readable code than the current alternatives.


Related issues 1 (0 open1 closed)

Has duplicate Ruby master - Feature #6222: Use ++ to connect statementsRejectedmatz (Yukihiro Matsumoto)03/29/2012Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0