Building a Rails Generator, and packing it into a gem

I started working on a generator that can get me started in a rails app for using MelonJS. Ryan Bates did a rails cast on creating one, and goes into more detail than I will if you need more specifics. However, you have to make sure you structure things correctly in your gem in order for it to be picked up.

You pretty much need to keep the same structure as given to you when you run

rails g generator melonjs

To create your separate project to work in, open your working directory, and add a lib/generators directory:

mkdir -p lib/generators

Copy the specific generator folder that you want from your rails project over, melonjs for example, and paste it in the newly created generators folder, so you have:


You'll need to add a require statement to the top of the generator so it loads rails properly:

# lib/generators/melonjs/melonjs_generator.rb

require 'rails/generators/base'

At the root of your project directory, create yourself a gemspec file, giving it the name of your generator. melonjs-generator.gemspec.

Here's the contents of my gemspec file for your refrence. You may need to do add required files to the gemspec if you have things like a readme or tests:

$:.push File.expand_path("../lib", __FILE__) do |s|        = "melonjs-generator"
  s.version     = "0.1"
  s.platform    = "ruby"
  s.authors     = ["Aaron McLeod"]       = [""]
  s.homepage    = ""
  s.summary     = %q{A rails generator for melonjs.}
  s.description = %q{This generator will put the melonjs library file in your vendor assets, and configure the asset pipeline to load it for you}
  s.files = Dir.glob("{lib}/**/*")
  s.require_path = 'lib'
  s.add_development_dependency 'rails', '~> 3.2.0'

And now, simply package and install the gem:

gem build melonjs-generator.gemspec
gem install melonjs-generator-0.1.gem

Back in your rails project, delete that particular generator from the lib/generators directory, and add your new gem to the Gemfile like you would any other. Run bundle install, and then see if your generator shows up via:

rails g --help

Hopefully that gets you sorted in building your own generator. The source code for mine if you need a reference can be found here.