在 Rails 3 生成器中多次调用任务
我正在编写一个 Rails 3 生成器来创建两个不同的模型。这是我想要做的一个非常简单的示例:
def my_generator_task
invoke "model", ["foo"]
invoke "model", ["bar"]
end
问题是 Thor invoke 方法 仅调用一次任务,因此永远不会发生对“model”任务的第二次调用,并且永远不会创建“bar”模型。有谁知道一种优雅的方法来实现这一点,最好是以一种不会破坏使用生成器运行“rails destroy”的能力的方式?
I'm writing a Rails 3 generator that creates two different models. Here's a very simplified example of what I'm trying to do:
def my_generator_task
invoke "model", ["foo"]
invoke "model", ["bar"]
end
The problem is that the Thor invoke method only invokes a task once, so the second call to the "model" task never happens and the "bar" model is never created. Does anyone know an elegant way to accomplish this, preferably in a way that doesn't break the ability to run "rails destroy" with the generator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
再想一想,这样也可以运行多个模型生成器而无需迁移
One more thought, this way it is also possible to run multiple model generator without migration
使用 Thor,如果你想调用一个没有依赖管理的任务,你只需直接调用它:
With Thor, if you want to invoke a task withOUT dependency management, you just call it directly:
如果您想运行一个从 Thor::Group 子类化的生成器,即不仅仅是单个 Thor 任务,您可以从任何不同的文件调用整个生成器。
Railties/rails 中的生成器模块generators.rb 似乎创建了一个新实例,因此它认为该任务尚未被调用。这意味着您可以根据需要多次重复上面的行,并且每次都会运行。
In case you want to run a generator that subclasses from Thor::Group, i.e. not just a single Thor task, you can invoke an entire generator from any different file.
The generators module generators.rb in railties/rails seems to create a new instance, so it doesn't think that the task has already been called. This means you can repeat the above line as many times as you want and it will run each time.
我不知道有什么优雅的方法可以做到这一点。在本次演讲中,我给出了一个调用
controller
生成器两次 - 查看幻灯片 43。不优雅的方法是进入 Thor 的
@_invocables
数组并删除第一次运行的任务,然后再运行它。I don't know of an elegant way to do that. In this talk, I gave an example of a custom generator that invokes the
controller
generator twice - check out slide 43.The inelegant way is to go into Thor's
@_invocations
array and delete the first run's tasks before running it again.有一个名为“行为”的宏方法可以提供帮助(使用 bonyiii 的示例):
或者只是:
there is a macro method called "behavior" can help(using bonyiii's example):
or just: