February 5, 2014

Creating a Ruby gem

There are different ways to create a new Ruby gem. I will show you how to do it with ease using bundler.

1) Generate all needed files.

$ bundle gem awesome_gem
      create  awesome_gem/Gemfile
      create  awesome_gem/Rakefile
      create  awesome_gem/LICENSE.txt
      create  awesome_gem/README.md
      create  awesome_gem/.gitignore
      create  awesome_gem/awesome_gem.gemspec
      create  awesome_gem/lib/awesome_gem.rb
      create  awesome_gem/lib/awesome_gem/version.rb
Initializing git repo in /Users/head/tmp/awesome_gem

This will create all needed files and prepare new rake tasks for you.

$ rake -T
rake build    # Build awesome_gem-0.0.1.gem into the pkg directory
rake install  # Build and install awesome_gem-0.0.1.gem into system gems
rake release  # Create tag v0.0.1 and build and push awesome_gem-0.0.1.gem to Rubygems

2) Edit gem specification in awesome_gem.gemspec.

3) Add your Ruby files to lib/awesome_gem and make sure that they are required from lib/awesome_gem.rb. Also do not forget to create own namespace (module) for your code.

# lib/awesome_gem.rb
require "awesome_gem/awesome_class"
require "awesome_gem/version"

module AwesomeGem
  # Your code goes here...
# lib/awesome_gem/awesome_class.rb
module AwesomeGem
  class AwesomeClass
    # ...

4) Add your tests to spec or test directory. Also make sure that they pass.

If you use RSpec then add this to your Rakefile.

require "bundler/gem_tasks"
require "rspec/core/rake_task"


task default: :spec

Then you can run your test just with rake command.

5) Install your gem locally and test if everything works as expected.

rake install

6) And publish it.

rake release

Above command will publish your gem to rubygems and tag current version in the git repository.

Further reading/watching

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.