I know there are several SO questions as well as online articles on using yield
in Rails. But I'm still having trouble understanding what's wrong with my code below, and would appreciate any advice.
In my app, I have:
A
controller
that passes data to thecommand
class'srun
method, and returns the request status based on the result of theCommand.run
(true
/false
)A
command
class that deals with the actual meat of the process, thenyields
true
if it succeeded, orfalse
if it failed
However, the command
class seems to be failing to yield
the results to my controller
. According to the error messages when I run my tests, it seems like my block in the controller
isn't being recognized as a block:
# If I use "yield result":
LocalJumpError: no block given (yield)
# If I use "yield result if block_given?":
# (This is because I have "assert_response :success" in my tests)
Expected response to be a <2XX: success>, but was a <400: Bad Request>
How should I rewrite the block (do ... end
part in the controller below) so that yield
works correctly? Or if the issue lies elsewhere, what am I doing wrong?
I've provided a simplified version of my code below. Thank you in advance!
# controller
def create
Command.run(params) do
render json: { message: 'Successfully processed request' }
return
end
render json: { message: 'Encountered an error' }, status: :bad_request
end
# command class
def run(params)
# Do some stuff, then send HTTP request
# "result" below returns true or false
result = send_http_request.parsed_response == 'ok'
yield result
end
def self.run(params)
new.run(params)
end
Note: This code works if I use if true... else...
in the controller instead of a block, and just return
the boolean result instead of yielding
it. But here I'd like to know how to make yield
work.