[英]Ruby on Rails Custom Generators with multiple sub generators
嗨,我正在尝试生成一个自定义生成器,所以我的自定义生成器是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.