Forum: Ruby on Rails include ClassMethods in plugins

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.
wyrosdick (Guest)
on 2007-01-19 19:03
(Received via mailing list)
Why is that in so many plugins I see people using (including
acts_as_taggable by DHH):

# init.rb
ActiveRecord::Base.send(:include, ActiveRecord::Acts::SomeModule)

# lib/some_module.rb
module ActiveRecord
  module Acts
    module SomeModule
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_something
          # code
        end
      end
    end
  end
end

why go through all that rather than just call:

# init.rb
ActiveRecord::Base.extend ActiveRecord::Acts::SomeModule::ClassMethods

and skip the self.included method?
Mark Reginald J. (Guest)
on 2007-01-20 12:52
(Received via mailing list)
wyrosdick wrote:
>    module SomeModule
>  end
> end
>
> why go through all that rather than just call:
>
> # init.rb
> ActiveRecord::Base.extend ActiveRecord::Acts::SomeModule::ClassMethods
>
> and skip the self.included method?

I guess the use of self.included paves the way for more complex things
to be done when the module included. It also allows the module to be
included into a single AR model or a class of AR models, rather than
into all of AR itself.

If you definitely want to apply the module to all of AR an even shorter
alternative is:

# lib/some_module.rb
class ActiveRecord
   def self.acts_as_something
     # code
   end
end

--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.