2

我正在尝试在我的 rails 4 应用程序中创建一个客户生成器。我跑了

rails g generator bootstrap

这在lib/generators/bootstrap. 包含bootstrap_generator.rb

class BootstrapGenerator < Rails::Generators::NamedBase
  source_root File.expand_path('../templates', __FILE__)
end

我希望这个生成器在我运行时挂接rake g model ...。我该如何实施呢?

4

2 回答 2

7

无论如何,我认为这不是干净但可行的解决方案:

配置/应用程序.rb

module YourApp
  class Application < Rails::Application
    config.generators do |g|
      g.orm             :concerns # to get run our generator under ActiveRecord
      g.test_framework  :rspec
    end
  end
end

lib/generators/rails/concerns/concerns_generator.rb

require 'rails/generators/active_record/model/model_generator'

module Rails
  module Generators

    hide_namespace 'concerns'

    class ConcernsGenerator < ActiveRecord::Generators::ModelGenerator
      source_root "#{base_root}/active_record/model/templates"

      def create_concern_file
        create_file "app/models/concerns/#{file_name}_concern.rb", <<-FILE
      class #{class_name}Concern

      end
        FILE
      end

      def create_concern_spec
        create_file "spec/models/#{file_name}_concern_spec.rb", <<-FILE
      require 'spec_helper'

      describe #{class_name}Concern
        pending "add some examples to (or delete) #{__FILE__}"
      end
        FILE
      end

    end
  end
end

这是给我们的:

$ rails g model Product name:string description:text
      invoke  concerns
      create    db/migrate/20131005122831_create_products.rb
      create    app/models/product.rb
      invoke    rspec
      create      spec/models/product_spec.rb
      create    app/models/concerns/product_concern.rb
      create    spec/models/product_concern_spec.rb
于 2013-10-05T12:34:11.837 回答
1

我不认为 rails 生成器在 rails 3 和 4 之间变化太大,所以这些 railscasts 应该仍然有帮助:

于 2013-10-11T01:53:46.963 回答