使用自定义 rake 任务向模型添加代码

发布于 2024-08-14 05:59:11 字数 351 浏览 2 评论 0原文

我写了一个简单的博客插件(它实际上是一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

就是爱搞怪 2024-08-21 05:59:11

您可以在插件中包含一个模型文件来打开 User 类并添加“has_many :posts”吗?

class User < ActiveRecord::Base
   has_many :posts
end

我认为这会起作用,因为您可以随时从任何文件打开 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"?

class User < ActiveRecord::Base
   has_many :posts
end

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.

芯好空 2024-08-21 05:59:11

您绝对可以通过 rake 任务访问您的模型。您必须确保将您的环境传递给它,以便它了解您的模型。例如,

desc"This will insert the Posts"

task(:insertPosts => :environment) do

#your code here

end

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,

desc"This will insert the Posts"

task(:insertPosts => :environment) do

#your code here

end
野侃 2024-08-21 05:59:11

这是一项需要实际修改源代码的任务吗?您是否考虑过添加一个模块?请提供您想要实现的目标的更多详细信息,以获得正确的指导。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文