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.

On Wed, Sep 10, 2008 at 11:32 PM, pepe [email protected] wrote:


Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
João Pessoa, PB, +55 83 8867-7208

Thanks Mauricio,

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

On Sep 10, 10:33 pm, “Maurício Linhares” [email protected]

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:

On Wed, Sep 10, 2008 at 11:40 PM, pepe [email protected] wrote:

Thanks Mauricio,

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


Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)
João Pessoa, PB, +55 83 8867-7208

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.

On Sep 10, 10:51 pm, “Maurício Linhares” [email protected]

Thanks so much to both. :slight_smile:

Pepe

On Thu, Sep 11, 2008 at 1:43 PM, pepe [email protected] wrote:

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?

That’s right.

Rails, RSpec and Life blog…

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.


Ryan B.
Freelancer
Skype: radarlistener
MSN & Gtalk: [email protected]

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

mark

Thanks to all. :slight_smile:

Pepe