Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

ruby on rails - Where should my non-model/non-controller code live?

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.

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.

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"?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what the 'lib' folder is for.

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

class MyFoo
end

in lib/my_foo.rb and then just by calling

MyFoo.new

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...