From yesterday’s code reading, I found that the restclient command uses RestClient::Resource for most of the work. So I’m going to start with it’s methods, starting with it’s HTTP verbs, #get.
The Code
1 2 3 4 5 6 7 8 9 10 11 |
module RestClient class Resource def get(additional_headers={}, &block) headers = (options[:headers] || {}).merge(additional_headers) Request.execute(options.merge( :method => :get, :url => url, :headers => headers), &(block || @block)) end end end |
Review
The #get method takes a hash of HTTP headers and a block. Since a Resource object is created with the url already, it’s doesn’t need to be passed into this method.
The first thing #get does is to merge the HTTP headers from it’s initialization (options[:headers]) and the additional headers from the method call. This way you can create one Resource object with common headers and then override them in each request as needed. Next, #get passes all of the data onto RestClient::Request#execute which I’m assuming would build and sent the actual HTTP request.
One interesting technique that is in #get is how it passes either the method’s block or initializer’s block into Request#execute. By checking for a nil object and using the & outside the parenthesis, this is a simple one liner.
1 |
&(block || @block) |