Ruby Gems or “gem” is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries. It is easy to manage and install to your system and it can be used by various rails applications.
Every RoR developer might have customised a gem at least once in his career, but not each one of them has actually, created a gem. Here, I am going to give a basic idea about how to create a new gem and how to publish it.
Kick off
Before starting please make sure that you are using the latest ruby version. RVM is really useful in this case;
How to name your Gem?
Don’t blindly give a random name to your gem. Please take care of the following;
Every dash represents a structure (folder, module) immersion
Every underscore represents a joining in the class name
Some examples:
gem new_test_gem
- require ‘new_test_gem’
- module/class NewTestGem
And:
gem gem-structure-new_test_gem
- require ‘gem/structure/new_test_gem
- module/class Gem::Structure::NewTestGem
How to create your Gem?
To create a gem;
$ bundle gem new_test_gem
It will create some basic files and directories.
Where to add your code or job
Your beautiful code goes here
# lib/new_test_gem.rb
Once you have added your code into the lib file then you will have to update the gemspec file;
# new_test_gem.gemspec
What is Gem Versioning?
# lib/new_test_gem/version.rb
module NewTestGem
VERSION = “0.1.0”
fin
A couple of things about what you create
- A gem version is a string of 3 numbers – ‘X.Y.Z’.
- Incrementing X, Y, Z
incrementing Z, a small change and it’s called the ‘build’ number(e.g. changing label/text) and no change in any functionality.
incrementing Y, a new functionality change and it’s called the ‘minor’ number. But no compatibility issues with the previously released versions.
incrementing X, severe change and it’s called the ‘major’ number and the change no longer compatible with the previous versions.
The gem below (Gem-release) helps you to version your gem with a simple ‘bump’ command.
Gem-release gem:
https://github.com/svenfuchs/gem-release
How to build your Gem?
Once we have our gemspec, we have to build a gem from it. We can, then, install it locally to test it.
Installation and Testing
Once your gem is built, you will have to install it to your system.
And of course, you have to test it properly.
$ gem install ./new_test_gem-0.1.0.gem
How to push your Gem?
To get it done, we’ll need to create an account on RubyGems.org.
Then, it will be available to the other rubyists all over the world through rubygems.org.
This is done by;
$ gem push new_test_gem-0.0.1.gem
To check it, your gem is added in RubyGems.org
$ gem list -r new_test_gem
The End
That’s all it takes to create a gem!
If you want to create a Ruby Gem, you can further read through the following write-ups;
http://guides.rubygems.org/make-your-own-gem/
http://railscasts.com/episodes/135-making-a-gem
https://gorails.com/episodes/creating-gems-for-frontend-javascript-libraries