Writing a Ruby gem!

For my final project, I’m working with Bonnie Mattson on a Ruby gem, currently called ‘Wikiwhat’, for the Wikipedia API! This is a really fun project, and also really challenging. The last few weeks of class have focused on working with frameworks and engines, and less on writing basic Ruby code, so it has been a nice change of pace.

One of the first challenges for this project has been getting the gem to build and install correctly. We use bundler to install and manage gems for our projects. Awesomely, we can also use it to build our gem too!

Here is a short outline of the process.

  1.  Use bundler to create a scaffold directory for the gem. This is nice because it takes care of a lot of details that are potentially easy to forget, like listing all the files that should be included in the gem.
bundle gem <GEMNAME>
  1. Write your gem! (no, it didn’t go that quickly, but you get the idea)

  2. Build your gem! A hint here is that you need to include the version number in your build command. Also, include the .gemspec file ending. (UPDATE: This is not where you include the version number. That is later!) EX: gemname.gemspec

gem build <GEMNAME>.gemspec

This will build your gem in the directory where you run this command.

  1. In the same directory, run the install command:
gem install <GEMNAME-version>.gem

It did take us quite a while to get to this point. We definitely had some malformed files and/or structure in our gem such that it either would not build or would not install. A few of the problems we had:

  • Bad require statements – It does not like it if things are named badly, or if you are trying to require '' or similar. I can’t remember why we thought we needed it, but you don’t! Don’t do it!
  • Incorrect naming or file structure – The gem builder/installer really really wants things to follow a semi-strict naming convention. Inside lib/, the main .rb file needs to be named the same as your gem name. If you have any additional code files, those need to be stored inside a folder that is named the same as your gem and main file.
    EXAMPLE:

    .
    ├── wikiwhat.gemspec
    └── lib
        ├── wikiwhat
        │   └── api_call.rb
        └── wikiwhat.rb

The final challenge was to be able to require it in IRB and run a command!

  1. Open IRB and require the gem:
require 'GEMNAME'

If it returns true, you’re 99% of the way there!

  1. Run a command! Obviously, this one is going to vary from gem to gem. If it works the way you expect, you are done! In our case, we ran our call method:
Wikiwhat.call("Albert Einstein")

And got back the first paragraph of the wiki article on Albert Einstein, just like we wanted. Yay!

 

Resources:

  1. So far, we have mainly used this great guide from RubyGems.org.

  2. I also really enjoyed this podcast on Ruby Gems from Ruby Rogues.

2 thoughts on “Writing a Ruby gem!

Leave a Reply

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