Skip to main content

Creating Your First Gem In Ruby on Rails

Creating Your First Gem In Ruby on Rails ?

RubyGems

The RubyGems package manager can download and install gems to your system and allows you to use the gems in other Ruby programs. Ruby 1.9 comes with RubyGems installed by default. If you are using a version prior to Ruby 1.9, you can download RubyGems here. To use RubyGems in a pre Ruby 1.9 app, you will need add this line
in your app:
require 'rubygems'

Ruby 1.9 does not need this line, since RubyGems is included in the language.
Gem Specification

As I mentioned before, the gem specification describes the gem. Let’s take a look at a basic gemspec file:
   
Gem::Specification.new do |s|
  s.name = %q{my_gem}
  s.version = "0.0.1"
  s.date = %q{2011-09-29}
  s.summary = %q{my_gem is an awesome gem}
  s.files = [
    "Gemfile",
    "Rakefile",
    "VERSION",
    "lib/my_gem.rb"
  ]
  s.require_paths = ["lib"]
end

The gemspec is a fairly simple file that describes various aspects of your gem. I am only listing the required attributes and the files in the example gemspec above. The first 4 attributes are self-explanatory. The “files” attribute lists all of the files that are included in the gem. The “require_paths” attribute specifies the directory that contains the Ruby files that should be loaded with the gem. For a complete list of the attributes that can be used in the gemspec, go here.

That is about as academic as I can get without falling asleep, so let’s cut to the chase and get to the good stuff.
Creating a Gem From Scratch
Create the basic file structure of the gem:

Fire up your shell and create the directories that will be needed in your gem:
$ mkdir awesome_gem
$ cd awesome_gem
$ mkdir lib

That’s it! You need a root directory for your gem and a lib directory to hold your Ruby file.
Create the gemspec

We will use the template from the previous section for our gemspec file. Create a file named “awesome_gem.gemspec” in your gem’s root directory. Then add some code to make a valid gemspec:
Gem::Specification.new do |s|
  s.name = %q{awesome_gem}
  s.version = "0.0.0"
  s.date = %q{2011-09-29}
  s.summary = %q{awesome_gem is the best}
  s.files = [
    "lib/awesome_gem.rb"
  ]
  s.require_paths = ["lib"]
end

This file contains the standard required attributes for a gemspec and shows that we have one file inside the “lib” directory. The file “awesome_gem.rb” in the lib directory is the main file that will be used to hold the Ruby code in this gem.
3. Add some code

To keep things simple, we will use only one Ruby file in this gem: /lib/awesome_gem.rb
You will see this type of structure in most gems you come across. The root file inside “lib” will usually match the name of the gem. In this case “awesome_gem” and “/lib/awesome_gem.rb”.

Go ahead and create this file and add the following code to it:
module AwesomeGem
  class WhoIs
    def self.awesome?
      puts "YOU ARE AWESOME!!"
    end
  end
end

This is not exactly code that will change the world, but at least the “awesome?” method will boost your self-esteem! This gem will allow you to use the class method “awesome?” from WhoIs in other Ruby programs. As I mentioned in the first section, RubyGems will install the gem in your app and give you access to the classes in your gem.
4. Generate the gem file

Now that you have some awesome code, you will want to create a gem so you can use this awesome code in another Ruby program. Rubygems has a command line interface that allows you to create a gem. Fire off this command inside the root directory of your gem:

$ gem build awesome_gem.gemspec

This command will build the gem and output a gem file that will include the version number in the file name. Since the gemspec contains a version attribute with a value of “0.0.0″, the gem file will be named awesome_gem-0.0.0. You should see the following output and some warnings about missing attributes:
Successfully built RubyGem
Name: awesome_gem
Version: 0.0.0
File: awesome_gem-0.0.0.gem

But you don’t care about warnings, because you are living on the edge and you are “awesome”. So you decide to move on and install this gem on your system. Notice that the gem file was created in your current directory.
5. Install the gem

Now that you have a gem file, you can use RubyGems to install the gem on your computer. Typically you install gems from external sources, but you are not restricted to that. If you have access to the gem file, you can install it locally by specifying the location of the gem file that will be installed. Here is the command to install awesome_gem.gem locally:
   
$ gem install awesome_gem.gemspec

You should get the following output:
   
Successfully installed awesome_gem-0.0.0
1 gem installed
Installing ri documentation for awesome_gem-0.0.0...
Installing RDoc documentation for awesome_gem-0.0.0...

Ah Yeah! You just created a gem! The gem is now installed on your system and ready to be used in another Ruby program.
6. Add The Gem to Another Ruby Program

Create a new Ruby file that will be used to test out our gem. Let’s call it “be_awesome.rb”. You can create this file anywhere on your system and then add the following code so we can use the “awesome?” class method from our gem. You just have to require ‘awesome_gem’ and RubyGems will be able to find the gem and make the class available to your program. Then you just call the class method from your namespaced class. Here is the code:
require 'awesome_gem'

AwesomeGem::WhoIs.awesome?

Now you can run the Ruby program and test out your newly created gem and see how awesome you are. Fire it up via the command line:
1
   
$ ruby be_awesome.rb

You should see the following output in your shell:
1
   
YOUR ARE AWESOME!

Congratulations, you just used your new gem in a program! I don’t think I would put that one on github and brag about it, but hey.. you still learned how to create a gem from scratch and use it in another program. Now you can move on to bigger and better things.
Conclusion

While this tutorial was fairly simple and only covered the basics of creating a gem, I think it is still very important information for those that are new to gem development. The basics will give you a good foundation for more advanced topics. I use Jeweler to create gems and while it is a great productivity tool, I feel that diving into generation tools before you create a gem from scratch can be harmful. You need to understand how to build a gem in the simplest form before you can understand the what is behind the code that a generation tool like Jeweler can give you. While I recommend building a gem from scratch when you are first learning gem development, I see absolutely no reason why you should not use a generator after you understand the basics. Generators are a huge time-saver since they give you a good skeleton to start with. The next blog post in this series will cover more advanced topics related to gem development, as well as a primer to using generation tools to give you a starting point for your gems. Later installments will explain how you develop gems for Ruby on Rails.

Stay tuned….

Comments

  1. It is nice blog Thank you provide important information and i am searching for same information to save my time Ruby on Rails Online Training

    ReplyDelete

Post a Comment

Popular posts from this blog

Create dynamic sitemap on ruby on rails

Sitemaps are an easy way for webmasters to inform search engines about pages on their sites that are available for crawling. In its simplest form, a Sitemap is an XML file that lists URLs for a site along with additional metadata about each URL (when it was last updated, how often it usually changes, and how important it is, relative to other URLs in the site) so that search engines can more intelligently crawl the site. It’s basically a XML file describing all URLs in your page: The following example shows a Sitemap that contains just one URL and uses all optional tags. The optional tags are in italics. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">    <url>       <loc>http://www.example.com/</loc>       <lastmod>2005-01-01</lastmod>       <changefreq>monthly</changefreq>     ...

Omniauth Linked in Ruby On Rails

def get_linkedin_user_data      omniauth = request.env["omniauth.auth"]      dat=omniauth.extra.raw_info      linked_app_key = "xxxxxxx"      linkedin_secret_key = "yyyyyyy"      client = LinkedIn::Client.new(linked_app_key,linkedin_secret_key)      client.authorize_from_access(omniauth['credentials']['token'],omniauth['credentials']['secret'])      connections=client.connections(:fields => ["id", "first-name", "last-name","picture-url"])      uid=omniauth['uid']      token=omniauth["credentials"]["token"]      secret=omniauth["credentials"]["secret"]   #linked user data     omniauth = request.env["omniauth.auth"]      data             = omniauth.info      user_name...

Error malloc(): memory corruption nginx with passenger?

Error malloc(): memory corruption nginx with passenger Passenger issue resolving steps :  sudo gem uninstall passenger(uninstall all passenger) sudo gem install passenger sudo passenger-install-nginx-module --auto --auto-download --prefix=/opt/nginx --extra-configure-flags=none Update nginx config file with new passenger version and restart the nginx