Rails 3 generators in gem

前端 未结 2 1877
说谎
说谎 2020-12-14 20:00

Might sound like a simple question, but I\'m stumped.

I\'ve created a gem that essentially contains a generator.

It contains the following structure:

相关标签:
2条回答
  • 2020-12-14 20:18

    If you use Railtie, you can define your generator wherever it could be using:

    generators do
        require "path/to/my_railtie_generator"
    end
    

    in Railtie class.

    0 讨论(0)
  • 2020-12-14 20:30

    This took a little bit for me to figure out, but I've run into the same problem. Here is how I fixed it.

    Tree structure looks like this:

    lib
      - generators
        - gemname
          install_generator.rb
          - templates
            (template files)
    

    Here's the code for install_generator.rb

    #lib/generators/gemname/install_generator.rb
    require 'rails/generators'
    module Gemname
      class InstallGenerator < Rails::Generators::Base
        desc "Some description of my generator here"
    
        # Commandline options can be defined here using Thor-like options:
        class_option :my_opt, :type => :boolean, :default => false, :desc => "My Option"
    
        # I can later access that option using:
        # options[:my_opt]
    
    
        def self.source_root
          @source_root ||= File.join(File.dirname(__FILE__), 'templates')
        end
    
        # Generator Code. Remember this is just suped-up Thor so methods are executed in order
    
    
      end
    end
    

    When I run rails g

    I see:

    Gemname
       gemname:install
    

    Some other things you may need to setup:

    #lib/gemname.rb
    module Gemname
      require 'gemname/engine' if defined?(Rails)
      # any additional requires
    end
    

    and

    #/lib/gemname/engine.rb
    require 'rails'
    module Gemname
      class Engine < Rails::Engine
      end
    end
    

    Some good references I've found on this are:

    • http://textmate.rubyforge.org/thor/Thor.html (take a look at the modules, especially Thor::Actions)
    • http://api.rubyonrails.org/classes/Rails/Generators/Base.html
    • http://api.rubyonrails.org/classes/Rails/Generators/Actions.html
    • https://github.com/wycats/thor/blob/master/README.md
    • http://www.themodestrubyist.com/2010/03/16/rails-3-plugins---part-3---rake-tasks-generators-initializers-oh-my/
    0 讨论(0)
提交回复
热议问题