Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 309
Darren Greaves Avatar asked Nov 12 '08 20:11

Darren Greaves


People also ask

What is the difference between model name and controller name?

Fundamentally, the model “knows stuff”. It holds, the business logic of a piece of data. On the other hand, the controller, “does stuff”.

What does a model do in Rails?

Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting.

What is a model Ruby on Rails?

6.1 Generating a Model A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.


1 Answers

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'

like image 161
Gareth Avatar answered Sep 23 '22 21:09

Gareth