Extends ActiveRecord from the application?

Hello,

I just want to create a method that will be available for all models. Is
it possible ?

On Wed, Feb 08, 2006 at 09:15:17PM +0100, oo00oo wrote:

I just want to create a method that will be available for all models. Is
it possible ?

I found this page (which has your answer) very very helpful:

http://wiki.rubyonrails.com/rails/pages/UnderstandingWhatMethodsGoWhere


- Adam

** Expert Technical Project and Business Management
**** System Performance Analysis and Architecture
****** [ http://www.everylastounce.com ]

[ Adam Fields (weblog) - - entertaining hundreds of millions of eyeball atoms every day ] … Blog
[ Adam Fields Resume ]… Experience
[ Adam Fields | Flickr ] … Photos
[ http://www.aquicki.com/wiki ]…Wiki
[ http://del.icio.us/fields ] … Links

Cool.

Well, I don’t want to add manually something to “ActiveRecord::Base and
include the module”

The other solution “to introduce a subclass of \ActiveRecord:Base and
implement the methods there.” sounds better. But how to do this ? Any
idea ?

On Feb 8, 2006, at 2:28 PM, oo00oo wrote:

Cool.

Well, I don’t want to add manually something to “ActiveRecord::Base
and include the module”

Is there a specific reason you don’t want to do this? This is
probably the more Rubyish way.

in lib/foo.rb

module Foo
module Bar
def my_new_method
end
end
end

ActiveRecord::Base.send :include, Foo::Bar

Now my_new_method is a part of ActiveRecord::Base and you can use it
from any of your models. This way you don’t have to change any of
your models and you’re using Ruby’s open classes, which makes you one
of the cool kids :slight_smile:

If you really need to subclass, you can do that like:

in app/models/myarsubclass.rb

class MyARSubclass < ActiveRecord::Base
def my_new_method
end
end

And then change all your models from:

class SomeModel < ActiveRecord::Base
end

to:

class SomeModel < MyARSubclass
end

But isn’t that a lot more work?

=dudley