Ruby 关于 Rails 具有多个子生成器的自定义生成器
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
您好,我正在尝试生成自定义生成器,所以我这里的自定义生成器是 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