使用自定义 rake 任务向模型添加代码
我写了一个简单的博客插件(它实际上是一个 Rails 引擎)。它旨在安装到已设置用户模型的应用程序中。
为了使我不必打开用户模型并手动插入“has_many :posts”,我想编写一个自动为我执行此操作的 rake 任务。
如果我将我的引擎打包为 gem 中的生成器,那么以下内容可能会起作用:
def manifest
record do |m|
m.insert_into "app/models/user.rb", 'has_many :posts'
end
end
这种事情可以通过 rake 任务完成吗?我环顾四周,找不到答案......提前致谢
I have written a simple blog plugin (it's actually a rails engine). It is designed to be installed into an app that already has a user model set up.
In order to save me from having to open up my User model and manually inserting "has_many :posts", I'd like to write a rake task that automatically does this for me.
If I were to package my engine as a generator inside a gem, then the following would probably work:
def manifest
record do |m|
m.insert_into "app/models/user.rb", 'has_many :posts'
end
end
Can this kind of thing be done with from a rake task? I've look around and I can't find an answer... thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在插件中包含一个模型文件来打开 User 类并添加“has_many :posts”吗?
我认为这会起作用,因为您可以随时从任何文件打开 Ruby 类;因此,无论使用您的插件的项目的模型文件夹中是否有 user.rb 文件,您的文件也将被加载,并且 has_many 将在运行时添加到 User 类中。
希望有帮助。
Can you include a model file in your plugin that would open up the User class and add the "has_many :posts"?
I think that would work because you can open Ruby classes at any time and from any file; so no matter if the project using your plugin has a user.rb file in his model folder, you file will also be loaded and the has_many will be added to the User class at runtime.
Hope it helps.
您绝对可以通过 rake 任务访问您的模型。您必须确保将您的环境传递给它,以便它了解您的模型。例如,
You can definitely access your model through a rake task. You have to be sure to pass it your environment though so that it knows about your models. For example,
这是一项需要实际修改源代码的任务吗?您是否考虑过添加一个模块?请提供您想要实现的目标的更多详细信息,以获得正确的指导。
Is this a task where actually modifying the source is appropriate? Have you considered including a module? Please give further details of what you're trying to achieve for correct guidance.