Forum: Ruby on Rails Extends ActiveRecord from the application ?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
oo00oo (Guest)
on 2006-02-08 22:15
(Received via mailing list)
Hello,

I just want to create a method that will be available for all models. Is
it possible ?
Adam F. (Guest)
on 2006-02-08 22:19
(Received via mailing list)
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/Understand...

--
				- Adam

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

[ http://www.aquick.org/blog ] ............ Blog
[ http://www.adamfields.com/resume.html ].. Experience
[ http://www.flickr.com/photos/fields ] ... Photos
[ http://www.aquicki.com/wiki ].............Wiki
[ http://del.icio.us/fields ] ............. Links
oo00oo (Guest)
on 2006-02-08 22:28
(Received via mailing list)
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 ?
Dudley F. (Guest)
on 2006-02-12 19:31
(Received via mailing list)
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 :)

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
This topic is locked and can not be replied to.