嗨,我正在尝试生成一个自定义生成器,所以我这里的自定义生成器是Myinitializer
,里面有myinitializer
。但我想里面有更多的发电机,就像Rails
和TestUnit
一样。我想 https://guides.rubyonrails.org/generators.html 但我找不到如何创建这些子生成器或它们的名称。我尝试在生成的目录(/lib/generator/myinitializer
(内创建一个新文件,但它没有做子生成器的事情。
rails -g
Rails:
application_record
assets
channel
...
system_test
task
ActiveRecord:
active_record:application_record
Myinitializer:
myinitializer
TestUnit:
test_unit:channel
test_unit:generator
test_unit:mailbox
test_unit:plugin
所以我想有这样的东西:
MyInitializer:
myinitializer
anothergeneratorhere
您可以使用公共模块包装生成器,以获得您所追求的命名空间(子生成器(效果。
module Foo
class Bar < Rails::Generators::Base
...
end
end
将产生一个名为foo:bar
的生成器。
rmlockerd 解释的内容只回答了一半回答了我的问题,这是有效的:
我使用rails g generator g1
和rails g generator g2
创建自定义生成器,并将它们组织到以下目录结构中:
# directory: /lib/generators
λ tree
.
└── gorking_generators
├── g1
│ ├── g1_generator.rb
│ ├── templates
│ └── USAGE
└── g2
├── g2_generator.rb
├── templates
└── USAGE
文件内容如下:
# file: g1_generator.rb
module GorkingGenerators
module Generators
class G1Generator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
end
end
end
# file: g2_generator.rb
module GorkingGenerators
module Generators
class G2Generator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
end
end
end
在此之后,我能够在使用rails g
时看到生成器就位:
GorkingGenerators:
gorking_generators:g1
gorking_generators:g2
然后,我可以使用以下方法使用它们:
rails g gorking_generators:g1