Create a Ruby Gem. Real World, play by play. Part 1
Regards ♨ – Minimul
Yet another Gem how to tutorial? No way, this one covers the making of a real Gem.
So you want to create a Ruby Gem but you desire a tutorial more advanced than extending the Ruby
String object with a 5 line method? With this tutorial you can follow my steps that led to the conception of a real library, the quickbooks-ruby-base Gem.
- Why do you want to create a Gem?
You make a Gem because you want to reuse code. You'll notice a pattern of something you're doing that you'd like to take across projects.
In my case, I do Quickbooks/Rails integration consulting so I was noticing a convention emerging where I was making a base class which would handle some of the dirty work when interacting with the "main" Ruby/QBO library,
- Starting point: The Gem name should be lowercase with the only special characters being hyphens and underscores.
- I was calling this class, 'QBBase', therefore, I settled on the Gem name 'quickbooks-ruby-base'.
- The quickbooks-ruby Gem simply uses the top-level namespace of 'Quickbooks'.
Quickbooks::Basewould appear to be good design but let me check that there is no conflicts.
$ irb >> require 'quickbooks-ruby' => true >> Quickbooks::Base NameError: uninitialized constant Quickbooks::Base from (irb):2 from /Users/christian/.rvm/rubies/ruby-1.9.3-p484/bin/irb:12:in `
bundle gemcommand to generate a Gem scaffolding.
$ cd ~/github/labs $ bundle gem quickbooks-ruby-base && cd $_
bundle gemcommand. I don't need the Ruby directory because
quickbooks-rubyonly uses the
Quickbooksnamespace. The proper directory structure follows the namespacing, which again, is to
quickbooks-ruby-base.gemspecfile to look like this:
git ls-filesremarks are located at the 11:40 mark.
git ls-filescommand in order this is how the the final
quickbooks-ruby-base.gemspecshould look in the figure below. Lastly, run the
- Create a blank
$ mkdir ~/github/labs/quickbooks-ruby-base/spec $ touch ~/github/labs/quickbooks-ruby-base/spec/spec_helper.rb
Rakefile, setting a default task that runs the specs.
require "bundler/gem_tasks" require "rspec/core/rake_task" RSpec::Core::RakeTask.new task :default => :spec task :test => :spec
spec/quickbooks_ruby_base_spec.rbwith the following basic test.
- First, I add the
- Next, add the
becommand. That is an alias for
require 'quickbooks-ruby-base'once the Gem is installed.
git ls-filesis still in order.
$ git add spec/ lib/ $ git ls-files # Verify output
- Edit the
spec/spec_helper.rbfile to properly reference the core Gem code.
- Edit the
spec/quickbooks_ruby_base_spec.rbfile to require the
Good place to stop for Part 1