从 Rails 3 插件中重新打开自动加载的类?

发布于 2024-09-28 08:33:42 字数 699 浏览 4 评论 0原文

我有一个 Rails 3 应用程序,它像平常一样定义了一些类。我试图弄清楚如何在插件中重新打开这些类之一(由“railsgenerateplugin...”生成),并自动拥有这两个文件(应用程序本身中的文件和插件中的文件)在开发模式下重新加载每个请求。

一个简单的例子是:

# root/lib/person.rb
class Person
  Core = 1
end

# root/vendor/plugins/plugin1/lib/person.rb
class Person
  Plugin = 2
end

# root/app/views/home/index.html.erb
<%= Person::Core %> ... <%= Person::Plugin %>

当渲染该视图时,我收到一条错误,指出 Bike::Plugin 未初始化。我已将 root/lib 和 root/vendor/plugins/plugin1/lib 添加到我的 autoload_paths 中(理想情况下,插件会将其添加到其 init.rb 或类似的地方,但一次只添加一件事)。

我该怎么办? autoload_at 看起来可能会有所帮助,如果我可以告诉它从两个位置显式自动加载 Person 类,但我没有任何运气(虽然我对它完全陌生,所以我可能传递了错误的参数等)。最后,我想使用标准位置(特别是模型)中定义的类来实现此目的,而不仅仅是 lib 。

I have a Rails 3 app that defines some classes like normal. I am trying to figure out how to reopen one of those classes within a plugin (generated by "rails generate plugin ..."), and have both of the files (the file in the app itself and the file in the plugin) automatically reload on every request in development mode.

A simple example would be:

# root/lib/person.rb
class Person
  Core = 1
end

# root/vendor/plugins/plugin1/lib/person.rb
class Person
  Plugin = 2
end

# root/app/views/home/index.html.erb
<%= Person::Core %> ... <%= Person::Plugin %>

When that view is rendered, I get an error that Bike::Plugin is uninitialized. I have added both root/lib and root/vendor/plugins/plugin1/lib to my autoload_paths (ideally the plugin would add that in its init.rb or somewhere similar, but one thing at a time).

How do I go about this? autoload_at kind of looks like it might help, if I can tell it to autoload the Person class from both locations explicitly, but I have not had any luck (I am completely new to it though, so I may be passing the wrong arguments, etc). In the end I want to do this with classes defined in the standard places (models in particular) and not just lib as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

软糖 2024-10-05 08:33:42

插件可以覆盖之前定义的任何类(无论是你的库,还是rails内部等)的早期定义的一个好方法:

#vendor/plugins/myawesomeplugin/lib/person.rb
Person.class_eval do
  Plugin = 2
  # override methods here too if you want
  def name
    "hacked"
  end
end

我之前使用这种方法来编写插件重载活动记录

但是,我不确定是否可以让插件在开发模式下自动重新加载,它们通常会重新加载仅当您在开发模式下重新启动服务器时。

one good way plugins can override earlier definitions for any class previously defined (either your libs, or rails internals etc):

#vendor/plugins/myawesomeplugin/lib/person.rb
Person.class_eval do
  Plugin = 2
  # override methods here too if you want
  def name
    "hacked"
  end
end

I've used this approach to write plugins before and overload active record

However, I'm not sure if it's possible to get plugins to auto reload in development mode, they usually reload only when you restart your server in dev mode.

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