Why do plugins use class_eval?


#1

I’m writing my own plugin and all the plugins I’ve seen use class_eval
in the
method that is called in the including module. For example:

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

module Foo
module Acts #:nodoc:
module Fox #:nodoc:

   def self.included(base)
     base.extend(ClassMethods)
   end

   # declare the class level helper methods which
   # will load the relevant instance methods
   # defined below when invoked
   module ClassMethods
     def acts_as_fox
       class_eval do
         extend Foo::Acts::Fox::SingletonMethods
       end
     end

Why is the class_eval needed here in acts_as_fox? Here self is the
module that
called acts_as_fox, which I’ve tested by adding a ‘puts self.name’ in
acts_as_fox. Isn’t self.class_eval redundant? The code could look like

     def acts_as_fox
       extend Foo::Acts::Fox::SingletonMethods
     end

So I don’t see the point of having that there.

I see the point of this code which is used to add the plugin into
ActiveRecord::Base since self is not ActiveRecord::Base:

ActiveRecord::Base.class_eval do
include Foo::Acts::Fox
end

but even here, couldn’t this be used instead?

ActiveRecord::Base.include Foo::Acts::Fox

Can anybody shed any light on this?

Regards,
Blair


Blair Z., Ph.D.
removed_email_address@domain.invalid
Subversion and Orca training and consulting
http://www.orcaware.com/svn/


#2

Can anybody shed any light on this?

#include is private, so you have to do:

ActiveRecord::Base.send :include, Foo::Acts::Fox


rick
http://techno-weenie.net


#3

Rick O. wrote:

Can anybody shed any light on this?

#include is private, so you have to do:

ActiveRecord::Base.send :include, Foo::Acts::Fox

OK, thanks.

That explains the second use of it, but not the first, right, since it’s
the
module itself that calls acts_as_fox, so it can call include (or extend)
on itself.

Regards,
Blair


Blair Z., Ph.D.
removed_email_address@domain.invalid
Subversion and Orca training and consulting
http://www.orcaware.com/svn/


#4

OK, thanks.

That explains the second use of it, but not the first, right, since it’s the
module itself that calls acts_as_fox, so it can call include (or extend) on itself.

I’m not sure. I don’t think I write my plugins that way.

  • checks

I guess I do! I should try taking those out and see if
acts_as_versioned still works. I don’t have my black belt in
metaprogramming…


rick
http://techno-weenie.net