Create your first gem in ruby.
Ever wondered how can you create your own library in ruby. Here’s a tutorial to create a simple library in ruby which ruby coders call gem.
RubyGems are package manger which are used to install various gems(libraries) to your system. Just like we use pip in python.
This file contains the specification of your gem that describes your gem.
Gem::Specification.new do |s|
s.name = "my_gem"
s.version = "0.0.1"
s.date = "2018-07-02"
s.summary = "My new gem"
s.authors = ["Shivam"]
s.files = ['lib/my_gem.rb']
s.require_paths = ["lib"]
Here s.name describes the name of your gem. Similarly, version, date and summary are self-explanatory. Now, s.authors describes the author of gem, s.files lists all the files that are included in gem and s.require_paths specifies the directory that contains the Ruby files that should be loaded with the gem.
Steps to create gem file:
Open your terminal and enter these commands:
Create the Gemspec file:
and copy the above code.
Add Files to your libray:
Copy the code below in your my_gem.rb file.
The root file inside “lib” will usually match the name of the gem.
Generate the Gem File:
Now we generate the gem file so that we can use this code in other ruby program.
Run this command on your terminal to generate gem file.
gem build my_gem.gemspec
Installation of My Gem:
Now we have our gem file, we can use RubyGems to install gem on our system.
gem install my_gem
Add this Gem File to another Ruby File:
Create a file.
Copy the code below in your addition.rb file.
You should see the following output: