Return from context above

This question is a little difficult to formulate, but I will do my best. There are fragments in our code, such as

response = do_something() return response unless response.ok? 

I was thinking of creating a wrapper method that would eliminate the need for this step, and it would look something like this.

 def rr(&block) response = yield unless response.ok? # somehow do return but in context above (magic needed here) end response end 

After that, I could minimize the code above to be

 response = rr { do_something() } 

It seems impossible, but it's Ruby , so maybe there is a way?

+6
source share
2 answers

The correct way to return to multiple levels of the stack when something goes wrong (which looks like what you are trying to do) is to throw an exception:

 class RequestFailedException < StandardError; end def rr(&block) response = yield unless response.ok? raise RequestFailedException, "Response not okay: #{response.inspect}" end response end 

Using:

 def do_lots_of_things() rr { do_something } rr { do_something_else } rr { another_thing } end begin do_lots_of_things rescue RequestFailedException => e # Handle or ignore error end 
+2
source

Would you just want to write a wrapper that does just that? Functionally, it seems that you are simply ignoring the answers ok? :

 def rr response = yield response.ok? ? response : nil end 

Maybe something is missing for me, but I don’t understand why you need to force return in a different context, which is not even possible.

0
source

Source: https://habr.com/ru/post/978336/


All Articles