REST is part of the Ruby Way. Which is why I’m surprised that every time I go to access a RESTful resource, I find myself writing some sort of ad-hoc rest client. Net::HTTP is too low level - you’ve got to write at least three or four fairly dense lines of code even for a relatively simple GET or PUT.
I was banking on ActiveResource being the defacto solution starting with Rails 2, but I was a bit disappointed when it was finally released. Its purpose is fairly narrow - accessing resources that are database-recordish and which operate completely in a certain XML format. But further, it doesn’t (as near as I can tell) support nested resources, which cuts out about 70% of what I might want to use it for.
The only other thing I can find is this, which monkey patches open-uri to handle other kinds of verbs. Fine, but still a bit too low level.
require 'rest_client' RestClient.get 'http://gemtacular.com/gems' RestClient.post 'http://myphotosite.com/users/adam/photos', File.read('pic.jpg'), :content_type => 'image/jpg' RestClient.destroy 'http://heroku.com/apps/myapp'
The middle one - post (or put) with a payload an non-xml content-type - is the one that interests me the most, and that I find hardest to do with other libraries. Particularly for a one-off on the command line. I’ll usually hobble together a curl command with a bunch of obscure switches that I can never remember. But now, I’ve just added require ‘rest_client’ to my .rush/env.rb, so at the rush command line I can instantly access any REST resource on the web with an easy-to-remember one-liner.
I also threw together a test server at rest-test.heroku.com, to try out all the different verbs. It just echoes back the verb, resource you requested (wildcard routing will match anything), and info about the payload. Here’s a session from my rush shell:
rush> RestClient.get "http://rest-test.heroku.com/some/resource" GET http://rest-test.heroku.com/some/resource rush> RestClient.put "http://rest-test.heroku.com/some/resource", home['pic.jpg'].contents, :content_type => 'image/jpg' PUT http://rest-test.heroku.com/some/resource with a 70335 byte payload, content type image/jpg rush> RestClient.delete "http://rest-test.heroku.com/some/resource" DELETE http://rest-test.heroku.com/some/resource
gem install rest-client if you’d like to give it a try. RDocs here.