如何在 Rails 3 的控制器中使用 mixin 或模块?
我的控制器中有一些行为,我将其提取到模块中,以便更好地测试并在一些地方重复使用它。关于此的两个问题:
- 哪里是放置我的模块的好地方?它们需要运行才能可供控制器使用,所以我想到了 config/initializers/ 目录。不过,这对我来说似乎有点可疑。
lib/
? - 如何确保代码运行,以便模块可
包含
到我的控制器中?
先生们,谢谢你们。
I have some behavior in my controller that I pulled out into a module in order to test better and re-use it in a few places. Two questions about this:
- Where is a good place to put my modules? They need to run in order to be available to the controllers, so I was thinking the
config/initializers/
directory. That seems a little suspect to me though.lib/
? - How do I ensure the code gets run so the modules are available to
include
in my controllers?
Thank you kindly sirs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
lib/
是放置模块的绝佳位置;比 config/initializers/ 好得多——至少在我看来。如果它是多个模块,或者是一个大模块,您还可以考虑将其制作为一个插件并将其放置在vendor/plugins
中。如果将其放入
lib/
中,则需要手动require
该文件。默认情况下,Rails 不会自动加载lib/
目录中的文件。您可以将 require 放入您的配置文件之一。我通常将额外的自动加载放在 config/application.rb 中。像这样的事情应该可以解决问题(假设您的
.rb
文件位于名为lib/my_module
的目录中):您必须确保您的模块是实际的 <代码>模块而不是<代码>类。然后,您可以简单地包含它:
lib/
is an excellent place for modules; much better thanconfig/initializers/
--at least in my opinion. If it's several modules, or one large one, you can also consider making it a plugin and placing it invendor/plugins
.If you put it in
lib/
, you'll need to manuallyrequire
the file. Rails, by default, does not autoload files in thelib/
directory. You can place the require in one of your config files.I usually put my additional autoloads in
config/application.rb
. Something like this should do the trick (assuming that your.rb
file is in a directory calledlib/my_module
):You have to make sure that your module is an actual
module
and not aclass
. Then, you can simply include it:1)我喜欢这样写:
我的类扩展在 app/extensions 下
我的模块位于 /app/mixins 下
我的服务位于 /app/services 下
2) 您可以配置应用程序以在 config/application.rb 中加载所有这些内容:
应该以正确的方式要求类扩展
并且 mixins 和服务可以添加到您的自动加载路径中
(我使用的是 Rails 3)
1) I like to put:
my class extentions under app/extentions
my modules under /app/mixins
my services under /app/services
2) You can configure your application to load all of these in config/application.rb:
class extentions should be required right way
and the mixins and services can be added to your autoload path
(I'm using rails 3)
尝试将控制器特定模块放入
app/controllers
中。不需要require
。Try putting controller specific modules in
app/controllers
. Norequire
required.