Back to home

Creating Your Own Ruby Gem main image

Creating Your Own Ruby Gem

This post will demonstrate how to create your own Ruby Gem.

It will the first in a three-part series that covers the following:

  1. Creating a Ruby gem.
  2. Deploying to the Ruby gem repository.
  3. Automating deployment with GitHub actions.

It will work off the code written in "RSpec With GitHub Actions".

Source code can be found here.

Prerequisites

  1. Basic familiarity with Bundler.
  2. Work through "RSpec With GitHub Actions".

Getting started

We will clone the project rspec-github-actions and use Bundler to initialize the project:

$ git clone https://github.com/okeeffed/rspec-github-actions.git $ cd rspec-github-actions # Checkout the starting point $ git checkout 1-rspec-with-github-actions # Make the related gemspec $ touch contrived_math.gemspec

At this stage, our project is now ready to start working with.

Updating our Gemspec file

Details about our Gem will be added into the contrived_math.gemspec file that was created.

I have filled out my details, and so it looks like so:

Gem::Specification.new do |s| s.name = 'contrived_math' s.version = '0.0.0' s.summary = 'Hello, World!' s.description = 'A simple hello world gem' s.authors = ["Dennis O'Keeffe"] s.email = 'hello@dennisokeeffe.com' s.files = ['lib/contrived_math.rb'] s.homepage = 'https://rubygems.org/gems/contrived_math' s.license = 'MIT' end

At this point, we can build the gem locally.

Building the gem

We can build the gem with a simple gem build command.

In the terminal, run the following:

$ gem build contrived_math.gemspec Successfully built RubyGem Name: contrived_math Version: 0.0.0 File: contrived_math-0.0.0.gem

Once built, it will output the file into the current working directory.

We can install that by referencing it directly:

$ gem install ./contrived_math-0.0.0.gem Successfully installed contrived_math-0.0.0 Parsing documentation for contrived_math-0.0.0 Installing ri documentation for contrived_math-0.0.0 Done installing documentation for contrived_math after 0 seconds 1 gem installed

Testing out our gem

At this point, we can test it our in an interactive environment.

Open up IRB and do just that:

$ irb irb(main):001:0> require 'contrived_math' \=> true irb(main):002:0> ContrivedMath.add(1, 2) => 3 irb(main):003:0> ContrivedMath.subtract(1, 2) => -1

Success!

Summary

Today's post demonstrated how to create our first Ruby gem.

In the next post, we will demonstrate how to deploy it to the gem package repository.

Resources and further reading

Photo credit: joshwithers

Personal image

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.