Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Ruby on Rails 3 gem with a generator (incl. namespace)

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.

like image 381
hjuskewycz Avatar asked Jun 22 '10 09:06

hjuskewycz


1 Answers

(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

like image 109
David Sulc Avatar answered Nov 24 '22 10:11

David Sulc