gem : rufus-verbs
‘rufus-verbs’ is an extended HTTP client library (gem). It provides the four main HTTP “verbs” as Ruby methods : get, put, post and delete.
It wraps a certain number of techniques that make it a decent tool for manipulating web resources.
features
currently :
* follows redirections
* automatically adds _method={post|put} in the request parameters with the option :fake_put => true
* HTTPS aware (‘verify none’ by default)
* HTTP basic authentication
* doesn’t propagate auth credentials in case of redirection to different host
* advertises and uses gzip compression
* proxy-aware (HTTP_PROXY env var or :proxy option)
* conditional GET (via ConditionalEndPoint class)
* request body built via a block (post and put)
maybe later :
* retry on failure
* greediness (automatic parsing for content like JSON or YAML)
* http digest authentication
* cache awareness
* head, options
some examples
At first, get the gem with
sudo gem install -y rufus-verbs
then
require 'rubygems'
require 'rufus/verbs'
include Rufus::Verbs
# using get(), post(), put() and delete() directly
r = get "http://en.wikipedia.org/wiki/Ruby"
puts r.body
r = get :uri => "http://en.wikipedia.org/wiki/Ruby"
puts r.body
post(
"http://resta.farian:780/inventory/tools/0",
:d => "hammer")
# passing the data via the :d (or :data) option
r = post "http://resta.farian:780/inventory/tools/1" do
"sliver bullet"
end
# the data is generated by a block
puts r.code.to_i
# 201... resource created, note that by default,
# an instance of Net::HTTPResponse is returned
puts get(
"http://resta.farian:780/inventory/tools/0",
:body => true)
# "sliver bullet" (directly returning
# the content of the response)
# oops, typo
put "http://resta.farian:780/inventory/tools/1" do
"silver bullet"
end
put "http://resta.farian:780/inventory/tools/1" do |req|
req['Content-Type'] = "text/plain"
"no silver bullet"
end
# the block accepts a 'req' (Net::HTTPREquest)
# argument
delete "http://resta.farian:780/inventory/tools/0"
# I don't need that hammer anymore
Using get() and co via an EndPoint to share common options for a set of requests :
ep = EndPoint.new(
:host => "resta.farian",
:port => 780,
:resource => "inventory/tools")
res = ep.get :id => 1
# still a silver bullet ?
res = ep.get :id => 0
# where did the hammer go ?
If your resource server allows it, you can take advantage of conditional GETs via rufus-verbs’ ConditionalEndPoint :
ep = ConditionalEndPoint.new(
:host => "resta.fariann",
:port => 780,
:resource => "inventory/tools")
res = ep.get :id => 1
# first call will retrieve the representation
# completely
res = ep.get :id => 1
# the server (provided that it supports
# conditional GETs) only returned a 304
# answer, the response is returned from
# the ConditionalEndPoint cache
the r[eal] doc
The documentation for ‘rufus-verbs’ is at http://rufus.rubyforge.org/rufus-verbs/
License is MIT.