钩入Rails模型生成器

时间:2013-10-01 17:28:31

标签: ruby-on-rails ruby ruby-on-rails-4

我正在尝试在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 ...时挂钩。我该如何实施呢?

2 个答案:

答案 0 :(得分:7)

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

<强>配置/ application.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 /发电机/轨道/关切/ 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

答案 1 :(得分:1)

我认为轨道发生器在轨道3和轨道4之间没有太大变化,所以这些轨道广播应该仍然有用: