Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from context above

Tags:

ruby

This question is little complicated to formulate but I will do my best. Trough our code we have snippets such as

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

I was think of writing wrapper method which would remove 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 would be able to minimize code from above to be

response = rr { do_something() }

Seems impossible but this is Ruby so maybe there is a way?

like image 794
Haris Krajina Avatar asked Nov 18 '14 14:11

Haris Krajina


People also ask

What does a context consumer require as a child?

Context.Consumer Requires a function as a child. The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.

What is a context API How does it work?

What is Context API? The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on.

What is Prop drilling and how can you solve it?

Prop drilling is the unofficial term for passing data through several nested children components, in a bid to deliver this data to a deeply-nested component. The problem with this approach is that most of the components through which this data is passed have no actual need for this data.


1 Answers

The correct way to return across multiple layers of the stack when something goes wrong (which appears to be what you are trying to do) is to raise an exception:

class RequestFailedException < StandardError; end

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

Usage:

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
like image 108
Ajedi32 Avatar answered Sep 21 '22 11:09

Ajedi32