Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Where do you put non-model code?

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.

like image 459
Derick Bailey Avatar asked Sep 24 '10 02:09

Derick Bailey


People also ask

Where do I put business logic Rails?

You can put business logic anywhere you want (even in views! though that's a bad idea). I'd say if the logic is tied to a real-world object, then put it on the model. Otherwise, use the controller.

What kind of logic doesn't belong to the model in Rails?

That logic belongs in app/models where our models are stored. A model is the M in MVC. Models contain business logic that interacts with the database. Business logic that doesn't interact with a database doesn't belong in a model.

What decides which controller receives which requests in Rails?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.


2 Answers

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.

like image 68
Nikita Rybak Avatar answered Sep 28 '22 03:09

Nikita Rybak


A 'common' suggestion is to say 'put this stuff in lib'. But there are other places to consider:

  1. Consider making a subfolder in app. Some examples include: app/workers, app/observers, app/sweepers, or whatever makes sense for you.

  2. Consider using config/initializers for initialization code.

  3. 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.

like image 26
David J. Avatar answered Sep 28 '22 02:09

David J.