Model Using Modules in Rails Application

前端 未结 2 1709
死守一世寂寞
死守一世寂寞 2020-12-28 08:49

I have a model that requires loading external data from an auxiliary source. A number of web services exist that my model can fetch the data from (swappable), but I don\'t w

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 09:38

    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.

提交回复
热议问题