The documentation for the rest_client gem has the following example:
RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block|
case response.code
when 200
p "It worked !"
response
when 423
raise SomeCustomExceptionIfYouWant
else
response.return!(request, result, &block)
end
}
How do you know what attributes are available on each block variable above? What attributes do response
, request
, etc. have respectively? When I run rest_client
:
response = RestClient.get('http://www.google.com')
lots of stuff are returned as response
:
response.instance_variables # => [:@net_http_res, :@args, :@request, :@code]
response.net_http_res # => #<Net::HTTPOK 200 OK readbody=true>
response.args # => {:method=>:get, :url=>"http://www.google.com", :headers=>{}}
response.code # => 200
What parts of response
are available to the block? Does the order of the parameters matter?
Typically, a method that accepts a block optionally will say something like this:
def f(...)
if block_given?
...
yield thing1, thing2...
...
return foo
else
...
return bar
end
end
Therefore, there does not need to be any correspondence between what is yielded to the block, and what is returned in case no block.
The way to know what the block receives is to look at the documentation for the method, or by consulting the source code.
Yes, order matters. The gem documentation specifically says RestClient#get
gives you response
, request
, result
and block
; it also describes what those things are.