To Craft a Gem…
Ruby has over 130,000 gems floating loose in the cavernous mines of the internet. For those who don’t quite know what a ruby gem is, a ruby gem is essentially a module of Ruby code that’s been wrapped up in a bundle, and hosted somewhere on the internet. Each gem has a specific use case, and if a developer needs it, all they need to do is put in one little line of code in their gem file like so, and they have access to the gem throughout their program.
Since there is such a vibrant open-source community supporting Ruby, the number of ruby gems out there only continues to grow. We know the good ones: rspec, pry, webpacker; but what if you, one day, found yourself in need of a gem that didn’t exist? What if you found yourself writing and rewriting the same code over again? What if you wanted the power to create your very own ruby gem?!
Well the good news is, it’s not actually that hard, and I’m going to break it down step by step.
- To start off, you’re going to want to create two separate files in your directory, one of which will be inside your lib folder. This is all mostly conventional, but what would we be without the sweet soothing embrace of convention? The first file, the one inside the lib file, should be a .rb file with the name of your gem as the name of the file.
Then in the same directory as your .lib file you’ll want to make a .gemspec file. The .rb file will contain all the meat of the gem, which is to say, where the actual command are going to be stored. The .gemspec file is going to contain all the logistical info about your gem, like the description, your name, the homepage for the gem, etc.
2. The .gemspec file! Let’s get the boring stuff out of the way first. There is a very particular syntax for how to craft your .gemspec file. If you have ever made a rail migration file, the syntax should look familiar.
Gem::Specification.new do |s|s.name = 'your_gem's.version = '0.0.0's.description = "The Best Gem You've Ever Made"s.authors = ["Thanos"]s.files = ["lib/your_gem.rb"]s.homepage = 'https://rubygems.org/gems/your-gem'end
There’s all sorts of specifications you can add to your gem. If you want a full list, head on over to the documentation.
3. It’s finally time make the gem itself! At this point, you’re going to want to be in the file that you’ve named after your gem, inside your lib directory. First define a class that has the name of your gem.
This will be the name of the library that you will use to invoke your gem’s methods when you are requiring it into another file. I.e.
But that comes later. Back to the meat of the gem. In your gem you’re going to create methods using this syntax:
def new_methodp "You made your very first method!"end
And there you have it. From that same file, you can load in as many useful methods as you want, and once you publish your gem, anyone can download it and reuse your tasty code.
For a quick primer on how to push your gem up to the cloud, check out this documentation.