Rails:你把非模型代码放在哪里?
我是 Rails 新手,一直在业余项目中学习 Rails 3。有时我想编写一些不属于我的模型或控制器的代码 - 与模型和/或控制器相关的问题,但我不想用实现细节来混淆它们中的任何一个我正在写的内容。
例如:我正在构建的项目使用 Janrain 的授权系统(RPX),因此我可以获得 oauth、openid、google 等授权。他们提供了大量的 API 代码,所以我不必自己编写它们。此代码不属于登录控制器或用户模块。它是授权代码,因此需要可由登录控制器访问,但它不是该控制器的一部分。
你把这段代码放在哪里?这不是型号代码。它不属于控制器。
... 提前致谢。
I'm new to Rails, and have been learning with Rails 3 on a side project. There are times when I want to write some code that does not belong in my models or in my controllers - concerns that are related to a model and/or controller, but i don't want to clutter up either of them with the implementation details of what i am writing.
For example: a project i'm building uses Janrain's authorization system (RPX) so i can get oauth, openid, google, etc. authorization. there's a nice chunk of API code that they provide so i don't have to write it all myself. this code doesn't belong in the login controller or in the user module. it's authorization code, so it needs to be accessible by the login controller, but it's not part of that controller.
Where do you put this code? it's not model code. it doesn't belong in the controller.
... thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用根目录中的
lib
文件夹(除非它在 Rails 3 中发生了更改)。您可以从那里引用类,而无需
require
语句。You should be able to use
lib
folder in your root directory (unless it's changed in Rails 3).You can refer classes from there without
require
statement.一个“常见”建议是“将这些东西放入
lib
”。但还有其他地方需要考虑:考虑在
app
中创建一个子文件夹。一些示例包括:app/workers
、app/observers
、app/sweepers
或任何对您有意义的内容。考虑使用
config/initializers
作为初始化代码。最后,只有当上述内容没有意义时,您才可以使用
lib
。不要忘记您可以使用子文件夹来防止它变得太垃圾。而且,一旦你让事情开始工作并完善,请考虑将你的代码提取到 gem 中。例如,请参阅 RailsCast 上的使用 Bundler 创建新 Gem。
A 'common' suggestion is to say 'put this stuff in
lib
'. But there are other places to consider:Consider making a subfolder in
app
. Some examples include:app/workers
,app/observers
,app/sweepers
, or whatever makes sense for you.Consider using
config/initializers
for initialization code.Lastly, and only if the above don't make sense, you can use
lib
. Don't forget you can use subfolders to keep it from getting too junked up.And, once you get things working and polished, consider extracting your code into gem. See, for example, the RailsCast on Creating a New Gem with Bundler.