Creating Your Own Ruby Gem
Published: Mar 19, 2022
Last updated: Mar 19, 2022
This post will demonstrate how to create your own Ruby Gem.
It will the first in a three-part series that covers the following:
- Creating a Ruby gem.
- Deploying to the Ruby gem repository.
- Automating deployment with GitHub actions.
It will work off the code written in "RSpec With GitHub Actions".
Source code can be found here.
Prerequisites
- Basic familiarity with Bundler.
- 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
Creating Your Own Ruby Gem
Introduction