Building API Wrapping Gems Could Not Get Much Easier

This post is by john from RailsTips - Home

Click here to view on the original site: Original Post

In which I show how easy it is now to create ruby gems that wrap APIs, using Google Weather as an example.

Google has a weather api that is dead simple to use. Just discovered that tonight so I whipped together a wrapper using HTTParty. I decided to try out Jeweler, a project by Josh Nichols, that makes creating gems a snap and it delivered. I used shoulda and fakeweb for the tests. Holy crap has making a gem that wraps a web service become really easy.

The New Way

  1. jeweler google-weather —shoulda —create-repo
  2. %w(matchy fakeweb).each { |x| require x } (in your test_helper)
  3. require ‘httparty’
  4. Add some code and tests
  5. rake version:bump:minor
  6. rake gemspec
  7. git push origin master
  8. blog

I did all of these in about an hour or two tonight.

The Old Way

  1. Create a bunch of files and directories and make a bunch of decisions
  2. mock and stub all net/http stuff
  3. net/http and rexml (or hpricot once that came along)
  4. Add some code and maybe some tests
  5. Add a version
  6. Figure out how to build a gemspec
  7. svn commit your files
  8. Request project to be created on rubyforge
  9. Wait a few days
  10. Project approved, release files, blog

And it would take a few days from first code scratched to gem released. My how times are a changing.

Stuff You Can Learn From This Gem

At any rate, the GoogleWeather gem I just created is a really simple example of how to use:

  • jeweler to create and manage a gem
  • httparty to pwn an API
  • shoulda to test the gem
  • fakeweb to make sure your tests aren’t making real web requests
  • matchy for some syntactical sugar

If you want to learn any of those things, poke around in the code a bit and you should be good to go. Also, if you want a really easy way to get weather information, this gem makes that possible.

Sorry I didn’t give it some fancy name like HTTParty or HappyMapper. Maybe I need to make another gem that spits out fancy names. After all, naming the project is the only thing left that is hard. 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.