How to use Basic Authentication with the Ruby Rest-Client gem

I hope this will save someone the hour that it just took me to google, try out several StackOverflow answers and finally finding the solution in the source code (note to self: move "check the source code" to the top of the list of things to try next time).

The code

So the trick is not to use the shorthand RestClient.get (or .post, .put etc.) methods since all options you pass in there are used as headers:

# Don't do this:

RestClient.get url, user: 'username', password: 'secret'

Instead, call RestClient::Request.execute directly, which is what the shorthand methods do:

# Do this instead:

RestClient::Request.execute method: :get, url: url, user: 'username', password: 'secret'

This works for RestClient 1.8.0 and from looking at the source of the latest version 2.0.0.rc1 it seems like it will continue to work. If you're using an earlier version, try it out and let me know whether it works for you in the comments!

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!