Skip to content

Instantly share code, notes, and snippets.

@jeremyolliver
Last active December 11, 2015 21:19
Show Gist options
  • Save jeremyolliver/4662034 to your computer and use it in GitHub Desktop.
Save jeremyolliver/4662034 to your computer and use it in GitHub Desktop.
Authouring gems - Namespaces, Rails Engines, and Templates

Writing Gems

Creating the project

There are several recommended ways to create the empty gem project.

For rails engines: it's best to update to the latest version of rails and generate it via rails (See http://guides.rubyonrails.org/engines.html). For regular rubygems, I recommend using either:

  • the bundler skeleton gem update bundler; bundle gem my_gem_name (note: you'll need to add rake as a development dependency)
  • Using my own gem template, which I've just updated (See https://github.com/jeremyolliver/gem_template)

Basics

  1. your_gem.gemspec defines dependencies and other details about the ruby gem
  2. By default rubygems will require "lib/your_gem". All code should be in there, and other files in lib/your_gem/* need requiring manually from lib/your_gem
  3. Write tests :)
  4. When testing your gem in progress with another project that will use it, in that project specify in Gemfile gem "your_gem", :path => "../path/to/your_gem/"
  5. Remember to fill in the Readme with what the aim of the project is for, and ideally basic usage too

Namespaces

Most ruby files should use snake_case and CamelCase conventions. Dashes should be avoided in most cases, the convention for when they should be used is when extending an existing namespace. Examples here include "rack-cache" extending the existing "rack" gem. In that case, an extended namespace of Rack::Cache is implied, which lends itself to code organisation such as "lib/rack/cache/*" though rubygems will still look to require the file "lib/rack-cache". It's nice to create the file "rack-cache", which requires the more idiomatic named files (slashes for namespace separation instead of dashes), without it, users will have to specify the file to require: gem "rack-cache", :require => "rack/cache".

Some of our gems follow a namespace convention with "easy-" Easy:: namespace in this fashion. If creating more like this, don't forget "lib/easy-gemname" to require "lib/easy/gemname" etc. (Example: https://github.com/AbleTech/easy-deployment/blob/master/lib/easy-deployment.rb)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment