从 Rails 3 插件中重新打开自动加载的类?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
插件可以覆盖之前定义的任何类(无论是你的库,还是rails内部等)的早期定义的一个好方法:
我之前使用这种方法来编写插件重载活动记录
但是,我不确定是否可以让插件在开发模式下自动重新加载,它们通常会重新加载仅当您在开发模式下重新启动服务器时。
one good way plugins can override earlier definitions for any class previously defined (either your libs, or rails internals etc):
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.