Isaac Sloan - How to Create a Ruby Gem

How to Create a Ruby Gem

1. Create your gem:

Here is the most modern approach to gem crafting:

bundle gem gemname
cd gemname

edit your_gem.gemspec and add description, summary, required gems and optional website. Add required gems for development such as rspec, rails or minitest to the Gemfile.

2. Add testing framework:

rspec --init
touch spec/your_gem_spec.rb
# Rakefile

require "bundler/gem_tasks"
require 'rake/testtask' do |t|
  t.libs << "test"
  t.pattern = 'test/*_test.rb'
  t.verbose = true
# test/gemname_test.rb

require 'gemname'
require 'minitest/autorun'
require 'minitest/pride'

describe Fixnum do
  it "must be instance of fixnum" do
    12.must_be_instance_of Fixnum

3. Add content to gem:

Add your code to lib/gemname.rb.

# lib/gemname.rb

require "gemname/version"
module Gemname
  #your code goes here

4. Push to the cloud:

In order to push to, first make sure that your gem is in a git repo and remember to set your version number in lib/gemname/version.rb

Option 1: Use the rake task

This will do the above for you in addition to tagging your git repo with the release number.

rake release
Option 2: The manual way
gem build gemname.gemspec
gem push gemname-0.0.1.gem

And thats it. Next time you make a change be sure to change the version number in version.rb.

November 10, 2014
comments powered by Disqus