17

I am trying to create a gem with a generator for Rails 3 (beta 4). I followed these instructions, and but I couldn't get it running. The problem is that when I am defining a module in the generator file, the generator gets listed with 'rails generate', but can't get executed because the generator isn't found.

From the instructions (doesn't work with 'rails generate my_gem:install'):

module MyGem
  class InstallGenerator < Rails::Generators::Base
    source_root File.expand_path("../templates", __FILE__)

    # all public methods in here will be run in order
    def add_my_initializer
      template "initializer.rb", "config/initializers/my_gem_initializer.rb"
    end
  end
end

Modified (works with 'rails generate install):

class InstallGenerator < Rails::Generators::Base
  source_root File.expand_path("../templates", __FILE__)

  # all public methods in here will be run in order
  def add_my_initializer
    template "initializer.rb", "config/initializers/my_gem_initializer.rb"
  end
end

However, I want to have namespaces for the generator, e.g. company:gem_name:generator, for which I have to use the module approach (I think). My guess is that it has something to do with the lookup and the directory structure, but I couldn't figure out how. I tried a couple of approaches:

lib
-generators
--my_gem.rb

lib
-generators
--company
---my_gem.rb

lib
-generators
--company
---my_gem_name
----my_gem.rb

but nothing helped. I also found quite a bit on the Internet, but non if showed what I needed.

hjuskewycz
  • 1,437
  • 1
  • 14
  • 20

3 Answers3

13

(I realize this post is nearly a year old, but hopefully this will at least be helpful to people coming here from a search.)

I implemented a namespaced generator for the (standalone) SugarCRM Ruby gem and wrote a blog post about this specific issue here: http://davidsulc.com/blog/2011/05/22/adding-a-namespaced-rails-generator-to-a-standalone-ruby-gem/

Alternatively, you can just look at the gem's code here: https://github.com/chicks/sugarcrm/commit/183c1b193e6620431826c3b594c568d4592fb0af

David Sulc
  • 25,946
  • 3
  • 52
  • 54
4

I know the rspec-rails gem has a generator named "rspec:install" which is only one namespace but maybe it's a start. So check out their source tree on github https://github.com/rspec/rspec-rails

Looks like the file structure is:

lib
 └ generators
    ├ rspec.rb
    └ rspec
       └ install
          └ install_generator.rb

I hope this helps lead you to a solution! Let us know what you find

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
0

the directory for your namespaced generator should be: lib/generators/my_gem

This is assuming the name of your gem is 'my-gem' or 'my_gem'. This may apply to other characters that are non-alphanumeric as well. If there's a hyphen, it will be replaced with an underscore.

This took me about 4 hours to figure out.

adamjk
  • 101
  • 1
  • 5