我的非模型/非控制器代码应该放在哪里? [英] Where should my non-model/non-controller code live?

查看:26
本文介绍了我的非模型/非控制器代码应该放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个遵循常规目录结构的 rails 应用程序(模型中的模型代码,控制器中的控制器代码).

I've written a rails app that follows the regular directory structure (model code in models, controller code in controllers).

但我现在正在开发一项新功能,为此我编写了一些(我称之为)服务"代码.
新功能是导入一些数据到系统中,目前是两个类进行导入,但可以扩展到更多.

But I'm now working on a new feature and for that I have written some (what I would call) "service" code.
The new feature is to import some data into the system, at the moment it's two classes to do the importing but could expand to more.

我不相信新代码属于模型,因为它没有对任何对象进行建模(它也不与任何单个对象直接相关.我当然不认为它属于控制器,因为它不是表示逻辑.

I don't believe the new code belongs in model as it's not modelling any object (it's not directly related to any single object either. I certainly don't think it belongs in controller either as it's not presentation logic.

所以,我创建了一个app/services"目录并将其放在那里.我还创建了一个test/services"目录,用于放置我的测试.

So, I've created a "app/services" directory and put it in there. I've also created a "test/services" directory where I have put my tests.

我认为一切都很好,但是当我运行rake:test"或autotest"时,我的新服务测试没有运行.
现在我希望有一种方法可以让耙子捡起它们,但这是我做错了什么的警告标志吗?
代码应该存在于其他地方还是我没有以Rails 方式"做事?

All well and good I thought but when I run 'rake:test' or 'autotest' my new services tests are not run.
Now I expect there is a way to make rake pick them up but is this a warning flag that I have done something wrong?
Is there some other place the code should live or am I somehow not doing things "the Rails way"?

通常每当我遇到这样的问题时,我通常会发现 rails 已经有解决方案,但我不知道约定.这是其中一种情况吗?

Generally whenever I've hit a problem like this before I've usually found that rails had a solution already, but I was not aware of the convention. Is this one of those cases?

推荐答案

这就是lib"文件夹的用途.

This is what the 'lib' folder is for.

lib 文件夹在自动查找的路径中,所以你可以有

The lib folder is in the automatically looked up path, so you can have

class MyFoo
end

lib/my_foo.rb 中,然后只需调用

in lib/my_foo.rb and then just by calling

MyFoo.new

从控制器加载代码,不需要 require 'my_foo'

from a controller the code will be loaded without you needing a require 'my_foo'

这篇关于我的非模型/非控制器代码应该放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆