Your First RubyGem
RubyGems has made it so easy to release open source software these days. This is just a quick write-up on how to push up your first gem.
Imagine we wrote a really cool Module for reversing text:
Module Reverser
def self.reverse(str)
str.reverse
end
end
and we wanted to release this as a gem. Start off with a basic directory structure:
$ mkdir -p lib/reverser # for your code
$ mkdir -p spec/examples # for your tests
For this simple gem, we drop our module code into ./reverser.rb
. If we had other modules or class definitions, they would be loaded (or autoloaded) from reverser.rb and stored in ./lib/reverser
The next thing we’ll need is a gemspec. A gemspec is just a ruby file that gives gemcutter details about your gem. Name this file reverser.gemspec
, and put it in your project’s root directory alongside lib
. The contents should look something like:
require 'lib/reverser/version'
spec = Gem::Specification.new do |s|
s.name = 'reverser' # the name of your library
s.author = 'John Crepezzi' # your name
s.add_development_dependency('rspec') # development dependency
s.add_dependency # dependency
s.description = 'reverser is an example library for reversing strings'
s.email = 'john@crepezzi.com' # your email address
s.files = Dir['lib/**/*.rb']
s.homepage = 'http://seejohnrun.github.com/reverser/'
s.platform = Gem::Platform::RUBY
s.require_paths = ['lib']
s.summary = 'example library for reversing strings'
s.test_files = Dir.glob('spec/*.rb')
s.version = Reverser::VERSION
s.rubyforge_project = 'reverser' # what rubygems will call this gem
end
Note, this is just a ruby file. You can do anything you need to in here, rather than wasting time using Jeweler or Hoe
You can see the full option set for the gemspec file in the reference. At the top of my gemspec you probably noticed I required another file, where I keep the version string. Create this file in lib/reverser/version.rb
:
module Reverser
VERSION = '0.0.1'
end
Now you’re at a point where you can build the gem: gem build reverser.gemspec
. That will produce reverser-0.0.1.gem
and if you want to test out your new creation, you can install it with gem install reverser-0.0.1.gem
.
Now the matter of pushing it to RubyGems, a simple gem push reverser-0.0.1.gem
will do the trick.
Of course you’re writing a bunch of tests along the way, so I definitely recommend reading an article I wrote about Rakefiles and how I use them to automate the whole process and make sure my tests always get run and my tags always get created in git.
Check out my GitHub projects for more examples, and get that gem out!