Model Using Modules in Rails Application

送分小仙女□ 提交于 2019-11-30 02:05:35

You are correct that if the module is tightly coupled to that specific model then it's not a good candidate for a gem/plugin.

app/helpers/ is for view helper methods and shouldn't contain modules that are solely for mixing into models.

One place you could put the module is within lib/. This is for code that doesn't really fit anywhere within app/ and is often the initial home of loosely coupled code before it is moved to a plugin (but that isn't a hard and fast rule). However, since your module is tightly coupled to your model, lib/ may not be the best place for it.

I know that 37signals (and others) use the concept of 'concerns' as a way of keeping related model code organised in modules. This is implemented by creating app/concerns/ and putting the modules in there. That directory is then added to the app's load path in config/application.rb (config/environment.rb for Rails 2) with:

config.load_paths += %W(#{Rails.root}/app/concerns)

The module can then be mixed into the model as normal.

Here's the original blog post about this by Jamis Buck - http://weblog.jamisbuck.org/2007/1/17/concerns-in-activerecord

Another variation of this which I personally prefer, although it doesn't involve modules, uses this plugin: http://github.com/jakehow/concerned_with

Hope that helps.

This link has helped me out around this.

http://ander.heroku.com/2010/12/14/concerns-in-rails-3/

I have been sticking it in a model/extensions directory. The concerns directory makes sense but the word 'concerns' doesn't feel obvious to me. Maybe it will grow on me.

I also added the extensions path in the application.rb

config.autoload_paths += %W(#{config.root}/app/models/extensions)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!