Where do I define a method so it's available to all models?

I’m trying to define a method that will be available to all Models. I
originally put it in the ApplicationHelper file, but I now understand
that this is only available to Views. Where do I put a common model
method then?

PS: If it makes a difference, the method needs to be able to reference
the calling model, i.e. passing the model instance as an argument

you can create a module mix you application_controller

On 11ÔÂ10ÈÕ, ÏÂÎç2ʱ25·Ö, Chris B. [email protected]

type error, must mix you model

Raecoo C. wrote:

you can create a module mix you application_controller
type error, must mix you model

On 11��10��, ����2ʱ25��, Chris B. [email protected]

I’m sorry, I don’t understand. Do you mean that I can add it to my
Application controller? According to the comments in that file, anything
added will be available to all controllers, but it doesn’t mention
models. I need it to be available to models, including when run from the
console.

WadeWinningham wrote:

You can write an extension to put in the lib/ directory and include it
in all of your models…

module MyExtension
def added_function
“stuff”
end
end

Ah, yes, OK. I figured it was something like that, but I just didn’t
know where to put it.


class MyModel < ActiveRecord::Base
include MyExtension
end

Or you could create a new base class that inherits from
ActiveRecord::Base and have your models inherit from your new base
class.

That makes sense too. Perhaps if I was adding more than one method. I’ll
go the route of the lib file and just require it.

Thanks!!

WadeWinningham is right

WadeWinningham wrote:

Or you could create a new base class that inherits from
ActiveRecord::Base and have your models inherit from your new base
class.

If I were to go this route and create a new base class, do i put it in
it’s own file in the model folder, and then do I require that file in
each related model, or in the application controller, or somewhere else?

Yes, you can put it in the model directory, mark it as an abstract
model class, and make sure it won’t collide with any other model.

You don’t have to explicitly call require in other models, just
specify it as the parent class, and Rails with automatically load the
specific file. Make sure to follow the Class name → filename
convention, so Rails can find it. Have Rails autoload it, so it can
reload the file when needed in development mode.

Thanks!

Mark
http://www.simpleteq.com

On Nov 12, 5:41 am, Chris B. [email protected]

You can write an extension to put in the lib/ directory and include it
in all of your models…

module MyExtension
def added_function
“stuff”
end
end


class MyModel < ActiveRecord::Base
include MyExtension
end

Or you could create a new base class that inherits from
ActiveRecord::Base and have your models inherit from your new base
class.

On Nov 10, 12:25 am, Chris B. [email protected]