Creating Your First Gem

Tweet

You see gems everywhere in the Ruby world. They are the backbone of just about every Ruby app out there. I’ll admit that I was a bit intimidated the first time I tried to create a gem, but I soon found out that it’s dead simple. In this blog series I will start by covering the basics of creating a gem from scratch, and then move on to more advanced topics including gem generation tools and Rails Engines. First things first, for all you Ruby newbies out there: What is a gem? Simply put, it is packaged Ruby code. At the bare minimum, a gem includes a Ruby file and a gemspec. The gemspec (gem specification) describes the gem and is used by the RubyGems package manager to install the gem.

RubyGems

The RubyGems package manager can download and install gems to your system and allows you to use the gems in other Ruby programs. Ruby 1.9 comes with RubyGems installed by default. If you are using a version prior to Ruby 1.9, you can download RubyGems here. To use RubyGems in a pre Ruby 1.9 app, you will need add this line
in your app:

require 'rubygems'

Ruby 1.9 does not need this line, since RubyGems is included in the language.

Gem Specification

As I mentioned before, the gem specification describes the gem. Let’s take a look at a basic gemspec file:

Gem::Specification.new do |s|
  s.name = %q{my_gem}
  s.version = "0.0.1"
  s.date = %q{2011-09-29}
  s.summary = %q{my_gem is an awesome gem}
  s.files = [
    "Gemfile",
    "Rakefile",
    "VERSION",
    "lib/my_gem.rb"
  ]
  s.require_paths = ["lib"]
end

The gemspec is a fairly simple file that describes various aspects of your gem. I am only listing the required attributes and the files in the example gemspec above. The first 4 attributes are self-explanatory. The “files” attribute lists all of the files that are included in the gem. The “require_paths” attribute specifies the directory that contains the Ruby files that should be loaded with the gem. For a complete list of the attributes that can be used in the gemspec, go here.

That is about as academic as I can get without falling asleep, so let’s cut to the chase and get to the good stuff.

Creating a Gem From Scratch

1. Create the basic file structure of the gem:

Fire up your shell and create the directories that will be needed in your gem:

$ mkdir awesome_gem
$ cd awesome_gem
$ mkdir lib

That’s it! You need a root directory for your gem and a lib directory to hold your Ruby file.

2. Create the gemspec

We will use the template from the previous section for our gemspec file. Create a file named “awesome_gem.gemspec” in your gem’s root directory. Then add some code to make a valid gemspec:

Gem::Specification.new do |s|
  s.name = %q{awesome_gem}
  s.version = "0.0.0"
  s.date = %q{2011-09-29}
  s.summary = %q{awesome_gem is the best}
  s.files = [
    "lib/awesome_gem.rb"
  ]
  s.require_paths = ["lib"]
end

This file contains the standard required attributes for a gemspec and shows that we have one file inside the “lib” directory. The file “awesome_gem.rb” in the lib directory is the main file that will be used to hold the Ruby code in this gem.

3. Add some code

To keep things simple, we will use only one Ruby file in this gem: /lib/awesome_gem.rb
You will see this type of structure in most gems you come across. The root file inside “lib” will usually match the name of the gem. In this case “awesome_gem” and “/lib/awesome_gem.rb”.

Go ahead and create this file and add the following code to it:

module AwesomeGem
  class WhoIs
    def self.awesome?
      puts "YOU ARE AWESOME!!"
    end
  end
end

This is not exactly code that will change the world, but at least the “awesome?” method will boost your self-esteem! This gem will allow you to use the class method “awesome?” from WhoIs in other Ruby programs. As I mentioned in the first section, RubyGems will install the gem in your app and give you access to the classes in your gem.

4. Generate the gem file

Now that you have some awesome code, you will want to create a gem so you can use this awesome code in another Ruby program. Rubygems has a command line interface that allows you to create a gem. Fire off this command inside the root directory of your gem:

$ gem build awesome_gem.gemspec

This command will build the gem and output a gem file that will include the version number in the file name. Since the gemspec contains a version attribute with a value of “0.0.0”, the gem file will be named awesome_gem-0.0.0. You should see the following output and some warnings about missing attributes:

  Successfully built RubyGem
  Name: awesome_gem
  Version: 0.0.0
  File: awesome_gem-0.0.0.gem

But you don’t care about warnings, because you are living on the edge and you are “awesome”. So you decide to move on and install this gem on your system. Notice that the gem file was created in your current directory.

5. Install the gem

Now that you have a gem file, you can use RubyGems to install the gem on your computer. Typically you install gems from external sources, but you are not restricted to that. If you have access to the gem file, you can install it locally by specifying the location of the gem file that will be installed. Here is the command to install awesome_gem.gem locally:

$ gem install awesome_gem.gemspec

You should get the following output:

Successfully installed awesome_gem-0.0.0
1 gem installed
Installing ri documentation for awesome_gem-0.0.0...
Installing RDoc documentation for awesome_gem-0.0.0...

Ah Yeah! You just created a gem! The gem is now installed on your system and ready to be used in another Ruby program.

6. Add The Gem to Another Ruby Program

Create a new Ruby file that will be used to test out our gem. Let’s call it “be_awesome.rb”. You can create this file anywhere on your system and then add the following code so we can use the “awesome?” class method from our gem. You just have to require ‘awesome_gem’ and RubyGems will be able to find the gem and make the class available to your program. Then you just call the class method from your namespaced class. Here is the code:

require 'awesome_gem'

AwesomeGem::WhoIs.awesome?

Now you can run the Ruby program and test out your newly created gem and see how awesome you are. Fire it up via the command line:

$ ruby be_awesome.rb

You should see the following output in your shell:

YOUR ARE AWESOME!

Congratulations, you just used your new gem in a program! I don’t think I would put that one on github and brag about it, but hey.. you still learned how to create a gem from scratch and use it in another program. Now you can move on to bigger and better things.

Conclusion

While this tutorial was fairly simple and only covered the basics of creating a gem, I think it is still very important information for those that are new to gem development. The basics will give you a good foundation for more advanced topics. I use Jeweler to create gems and while it is a great productivity tool, I feel that diving into generation tools before you create a gem from scratch can be harmful. You need to understand how to build a gem in the simplest form before you can understand the what is behind the code that a generation tool like Jeweler can give you. While I recommend building a gem from scratch when you are first learning gem development, I see absolutely no reason why you should not use a generator after you understand the basics. Generators are a huge time-saver since they give you a good skeleton to start with. The next blog post in this series will cover more advanced topics related to gem development, as well as a primer to using generation tools to give you a starting point for your gems. Later installments will explain how you develop gems for Ruby on Rails.

Stay tuned….

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Ernest Shulikovski

    Helpful, for anyone who has never created a gem yet.
    I am looking forward for post about creating gems for RoR.

  • geronimo

    Great post, thanks for sharing !

  • Neeti

    awesome tutorial with baby steps towards gem creation unlike Most of the other scaringly complex tuts that discourage novices in gem world

  • http://www.microspino.com Microspino

    Beautiful! The intro i was searching for.

  • http://dominik.honnef.co Dominik Honnef

    It’s not often that I see tutorials describing how to build gems _without_ tools like (ec)hoe, Newgem and whatever the various (in my opinion useless) tools are named, so big kudos for that. Explaining how to manually write a gemspec is definitely the most important part of “How to create gems” tutorials, and yet most forget exactly that part.

    Minor correction though: “Rails 1.9 does not need this line, since RubyGems is included in the language” ← Surely you meant to say “Ruby 1.9″, not “Rails 1.9″ :)

    And even for 1.8 it’s better to use the RUBYOPTS environment variable to load Rubygems, so that your code doesn’t depend on Rubygems, but just on the fact that _some_ kind of package manager correctly sets up the load paths, which could be your system’s package manager or a basic shell script.

  • http://www.redalchemist.com Brooke Kuhlmann

    In case it is of interest, here is my Gemsmith (https://github.com/bkuhlmann/gemsmith) gem that aids in building new Ruby Gems. It is still very important to understand the basics of Gem building as this article illustrates but should you get tired of the manual work and desire something automated with custom settings, then this might be up your alley (oh, and it helps if you like Bundler).

  • Tsegas

    Nice tutorial, been looking for something like this for a while now. Just two possible correction points:

    1. In the “awesome_gem.gemspec” file you need to add the authors entry, e.g.

    s.authors = ["Your Name"]

    2. The command to install the gem after successfully creating it is:

    gem install awesome_gem-0.0.0.gem

    it should refer to the .gem file not the .gemspec

    Hope this helps.

    • http://biske.rs Иван Бишевац

      I agree. After adding authors to gemspec it worked.
      Also, it shouldn’t be installed .gemspec but .gem file.

  • Jack Zelig

    Great tutorial. Thanks very much.
    I just successfully build my first gem and it was completely painless!
    I look forward to future installments.

    One small typo in the last code block:
    It currently reads “YOUR ARE AWESOME!”, that’s one ‘r’ too many on the ‘you’.

  • Odair Silva

    Tks! That’s the easy kind of information noobs are looking for their first steps.
    Tks again!

  • Faiz

    Awesome…
    thanx man.

  • Andy R.

    Minor correction though: to install the gem, you need to write ‘gem install gem_file.gem’, and not ‘gem install gem_file.gemspec’. Apart from that, awesome post again!

  • http://www.dingzhihu.com dingzhihu

    great post for newbies

  • Sachin Gevariya

    Great tutorial for Beginners…. Thanx..

  • Suchitra Edussuriya-Essl

    Hi, Extreme Newbie here. I am using Windows to learn Ruby & Rails. In order to create the Gem, should I start the Command prompt with Ruby ?

    Thanks

  • Harikrishna Kanta

    It should be

    gem install awesome_gem

  • Harikrishna Kanta

    gem install awesome_gem ————>>correct

    gen install awesome_gem.gemspec ———->>wrong

  • Harikrishna Kanta

    gem install awesome_gem ————>>correct

    gem install awesome_gem.gemspec ———->>wrong