Common models code - where to put it?

Hello.

I have some code that I want to share between my models (i.e.: text formatting routines). Where would be the correct place to put it?

Thanks in advance.

Pepe

Ideally, you should write a plugin, more on that here -> https://peepcode.com/products/rails-2-plugin-patterns

But you could also just create a simple module and make your models include it.

Thanks Mauricio,

If I write the module, do I just put it in the folder where all the modules are?

No, you could put it at the "lib" folder and add a require for it in your user model.

Putting your module at the helpers folder would make it be included in your view helpers, and i think this is not what you're looking for :slight_smile:

Sorry, I should have said where all the 'models' are.

Sorry if I am little dense here but it's the first time I do this and I want to make sure I understand.

I create a module ('my_module.rb') with my code and just drop the file in folder 'lib', not in 'lib/tasks'. Then I issue a require 'my_module' in my models and I'm ready to rock & roll?

Thanks again.

That's right.

Thanks so much to both. :slight_smile:

Pepe

Actually I think the module will be automatically included if you put it in the "lib" folder. You dont have to "require" it.

mark

You could define the model like this, as a file called lib/shared_methods.rb

module SharedMethods    def to_s      name    end end

and then just type include SharedMethods in any model you want to have that to_s method.

Thanks to all. :slight_smile:

Pepe