Create a Simple Ruby Gem

Ferris Boran
The Startup
Published in
3 min readJun 20, 2019
It’s a ruby

Make the Basic Folders

Every gem needs at least a root folder and a lib folder. In terminal, enter the following:

$ mkdir my_gem
$ cd my_gem
$ mkdir lib

Or copy and paste: mkdir my_gem && cd my_gem && mkdir lib

Create the First Gem Code

Make the name of the file the same name as the gem. This file is solely responsible for setting up your gem. You can still break up your code into different files but make sure your main gem file has access to it by adding require '<path to file>' .

$ cd lib
$ > my_gem.rb

Or copy and paste: cd lib && > my_gem.rb

> is just a shortcut for touch

Add Some Function

# ./lib/my_gem.rbmodule MyGem
class Here
def self.here?
puts "Ferris was here"
end
end
end

You don’t have to put it in a module:

# ./lib/my_gem.rbclass MyGem
def self.here?
puts "Ferris was here"
end
end

Create the gemspec File in the Root Directory

$ > my_gem.gemspec

The gemspec file holds the information about the gem.

There are 5 required fields:

  • name — The name of your gem
  • version — The current version of your gem
  • summary — A summary of what your gem does
  • authors — Who wrote the gem
  • files — The files needed to make your gem function (Your gem will still build without files listed but it won’t work)

There are 2 fields that will populate a warning if they are not present:

  • homepage — Website for your gem
  • license — Lets users know what and how they are allowed to use your gem

A couple of recommended fields:

  • description — A description of your gem
  • email — Your contact email
# ./my_gem.gemspecGem::Specification.new do |s| 
### REQUIRED ###
s.name = 'my_gem'
s.version = '0.0.0'
s.summary = "This is My_Gem"
s.authors = ["Ferris Boran"]
s.files = ["lib/my_gem.rb"]
### WARNING ###
s.homepage = 'https://mygem.com'
s.license = 'OML'
### RECOMMENDED ###
s.description = "A simple test gem" # nice to have
s.email = 'ferris@email.com # nice to have
end

Build and Install

$ gem build my_gem

If all goes well you should see something like this in your terminal

$ Successfully built RubyGem
Name: my_gem
Version: 0.0.0
File: my_gem-0.0.0.gem

$ gem install my_gem-0.0.0.gem

Same as before, you should get back something like this

$ Successfully installed my_gem-0.0.0
Parsing documentation for my_gem-0.0.0
Done installing documentation for test after 0 seconds
1 gem installed

Require Your Gem and Use It

Add it to your Gemfile

# <your app>/Gemfilegem 'my_gem'

Require it require 'my_gem' wherever you need it

### If using a module ###require 'my_gem'class WhoWasHere < MyGem::Here
self.here?
end
### If using a class ###require 'my_gem'MyGem.here?

Now when you run your app your gem will do what you designed it to do!

Module Example
Class Example

Sources

--

--