Tuesday, 2 September 2014

Steps for creating gem



Just to make sure you have bundler gem installed. 
  • $ gem install bundler
Now as bundler is installed, you just need to choose name for your gem, in this case "gem-post".
  • $ bundle gem gem-post
This creates the "gem-post" directory with following gem structure :
  • $ tree gem-post
    ├── .gitignore
    ├── Gemfile
    ├── LICENSE.txt
    ├── README.md
    ├── Rakefile
    ├── gem-post.gemspec
    └── lib
        ├── gem-post
        │   └── version.rb
        └── gem-post.rb
Let's first look at the gemspec file (gem-post.gemspec in this case). This file contains metadata about the gem, such as the name, description, author, license, and any gem dependencies required for it to work.

  • # coding: utf-8
    lib = File.expand_path('../lib', __FILE__)
    $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
    require 'dogeify/version'
    Gem::Specification.new do |spec|
      spec.name          = "gem-post"
      spec.version       = GemPost::VERSION
      spec.authors       = ["Author Name"]
      spec.email         = ["[email protected]"]
      spec.description   = %q{A short description!}
      spec.summary       = %q{A short description!}
      spec.homepage      = ""
      spec.license       = "MIT"
      spec.files         = `git ls-files`.split($/)
      spec.executables   = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
      spec.test_files    = spec.files.grep(%r{^(test|spec|features)/})
      spec.require_paths = ["lib"]
      spec.add_dependency 'engtagger'
      spec.add_development_dependency 'bundler', '~> 1.3'
      spec.add_development_dependency 'rake'
      spec.add_development_dependency 'rspec'
Now, just take a look at lib/gem-post.rb and lib/gem-post/version.rb files. These two files are initially very simple.

First start with version.rb :
  • module GemPost
      VERSION = "0.0.1"
This file contains only the version number.

Now, look at the gem-post.rb :
  • require "gem-post/version"
    module GemPost
      # This is the place, where you will put your GEM code.
Replace comment with your GEM code.

And, thats it, you are ready with your first gem to be released.

How to release a GEM

  • Prerequisites :
  1. You must commit your GEM files to GIT, as Bundler assumes that you're working with some sort of git repository.
  2. You must have an account on rubygems.org in order to release your gem.

Now, as you have both the prerequisites setup, you can simply run :
  • $ bundle exec rake release
This will release your gem, which will accessible through rubygems.org.

As its been released now, you can add this "gem-post" gem into your Gemfile.

Updating GEM

  1. Make changes into your GEM code,
  2. Update the version in lib/gem-post/version.rb file, 
  3. Make a commit of your changes, and run : 
    • $ bundle exec rake release
 Updated gem version will be relesed on rubygems.org and will be available to use it into your Gemfile.