Adding a namespaced Rails generator to a standalone Ruby gem

Posted on May 22, 2011

I wanted to add a generator to the SugarCRM ruby gem, but couldn’t find any straightforward resources on doing just that: taking a standalone ruby gem, and adding a generator that is available from within a Rails environment. To make matters more interesting, I wanted this generator to be namespaced: instead of calling `config`, I wanted to call `sugarcrm:config`.

Before diving into this short explanation of how I implemented the namespaced generator within a ruby gem, it would be a good idea to read this rails guide on generators to have a general understanding of how the basic case works.

(For those of you who want just the code, it's here.)

File storage

First things first: where should the generator files go? As explained in the generator rails guide, they should go into a rails/generators folder. But since I wanted a namespaced generator, I needed to used a slightly different path. I wanted the generator to be called with rails generate sugarcrm:config , so my path ended up being rails/generators/sugarcrm/config/config_generator.rb (note: the source files for the gem were in a lib folder, and all of these files and paths are also within that lib folder).

The templates for this generator were put in rails/generators/sugarcrm/config/templates/.

In other words, the base folder for the generator is namespace/generator, and will contain the actual generator and the templates folder.

Namespacing the generator

To namespace the generator, you need to put it within a module, like standard ruby code:

  
  
    module Sugarcrm
  module Generators
    class ConfigGenerator < Rails::Generators::Base
        # ...
    end
  end
end
  
  

And that all there is to it. You'll now be able to call rails g sugarcrm:config to execute the generator! (Make sure to check out the actual code to see the parts I didn’t cover in sufficient detail.)


Would you like to see more Elixir content like this? Sign up to my mailing list so I can gauge how much interest there is in this type of content.