开发者

Rails: Where do you put non-model code?

开发者 https://www.devze.com 2023-01-17 22:04 出处:网络
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 rela

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消