Creating a Basic Gem

Episode #99 by Teacher's Avatar David Kimura

Summary

Gems are a packaged library of functions that can extend your application or provide other features to your system. Learn to create and publish a ruby gem.
ruby gem 9:32

Resources

Summary

# Terminal
# Create gem template
bundle gem leftpad

# Run specs test
rspec spec

# Build and compress the gem
gem build leftpad.gemspec

# Publish gem to rubygems.org
gem push leftpad-1.2.1.gem

# Install specific gem from local file
gem install leftpad-1.2.1.gem

# Uninstall gem from local source
gem uninstall leftpad

# Install gem from rubygems.org
gem install leftpad

# leftpad.gemspec
# coding: utf-8
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "leftpad/version"

Gem::Specification.new do |spec|
  spec.name = "leftpad"
  spec.version = Leftpad::VERSION
  spec.authors = ["Dave Kimura"]
  spec.email = ["support@driftingruby.com"]

  spec.summary = %q{A gem for left padding text.}
  spec.description = %q{This gem is forever.}
  spec.homepage = "https://www.driftingruby.com/episodes/creating-a-basic-gem"
  spec.license = "MIT"

  spec.files = `git ls-files -z`.split("\x0").reject do |f|
    f.match(%r{^(test|spec|features)/})
  end
  spec.bindir = "exe"
  spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
  spec.require_paths = ["lib"]

  spec.add_development_dependency "bundler", "~> 1.15"
  spec.add_development_dependency "rake", "~> 10.0"
  spec.add_development_dependency "rspec", "~> 3.0"
  # spec.add_dependency "rspec", "~> 3.0"
end

# Gemfile
source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# Specify your gem's dependencies in leftpad.gemspec
gemspec

# lib/leftpad.rb
require "leftpad/version"

module Leftpad
  def leftpad(chars, filler = ' ')
    self.rjust(chars, filler)
  end
end

class String
  include Leftpad
end

# lib/leftpad/version.rb
module Leftpad
  VERSION = "1.2.2"
end

# spec/leftpad_spec.rb
require "spec_helper"

RSpec.describe Leftpad do
  it "has a version number" do
    expect(Leftpad::VERSION).not_to be nil
  end

  it "leftpad with no padding char" do
    expect('left'.leftpad(8)).to eq(' left')
  end

  it "leftpad with padding char" do
    expect('left'.leftpad(8, '0')).to eq('0000left')
  end

  it "leftpad with fewer padding char" do
    expect('left'.leftpad(2, '0')).to eq('left')
  end
end